@stacksjs/rpx 0.11.29 → 0.11.31
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 +198 -198
- package/dist/chunk-9amtxw74.js +252 -0
- package/dist/{chunk-ws2cmbxh.js → chunk-axym4f9k.js} +1 -1
- package/dist/{chunk-z86swbd8.js → chunk-qfckr5a3.js} +11 -11
- package/dist/chunk-xbct09d3.js +1 -0
- package/dist/index.js +2 -2
- package/dist/start.d.ts +6 -1
- package/dist/utils.d.ts +12 -0
- package/package.json +2 -2
- package/dist/chunk-22h4jf2c.js +0 -1
- package/dist/chunk-9dh9jhc6.js +0 -252
package/dist/bin/cli.js
CHANGED
|
@@ -1,258 +1,258 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
3
|
#!/usr/bin/env bun
|
|
4
|
-
import{createRequire as zK}from"node:module";var WK=Object.defineProperty;var BK=($)=>$;function jK($,w){this[$]=BK.bind(null,w)}var EB=($,w)=>{for(var Y in w)WK($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:jK.bind(w,Y)})};var t=($,w)=>()=>($&&(w=$($=0)),w);var b=zK(import.meta.url);import{existsSync as hB,statSync as DB}from"fs";import{existsSync as q7,mkdirSync as MI,readdirSync as II,readFileSync as E7,writeFileSync as VI}from"fs";import{homedir as ew}from"os";import{dirname as yI,resolve as Y$}from"path";import vA from"process";import{existsSync as kB,statSync as xB}from"fs";import{existsSync as iJ,mkdirSync as T7,readdirSync as f7,writeFileSync as H7}from"fs";import{homedir as $1}from"os";import{dirname as PB,resolve as i0}from"path";import kw from"process";import{join as R7,relative as M7,resolve as bB}from"path";import yA from"process";import{existsSync as Rj,mkdirSync as PI,readdirSync as bI,writeFileSync as uI}from"fs";import{homedir as MJ}from"os";import{dirname as iI,resolve as c0}from"path";import KY from"process";import{join as I7,relative as V7,resolve as uB}from"path";import OA from"process";import{existsSync as Mj,mkdirSync as nI,readdirSync as pI,writeFileSync as rI}from"fs";import{dirname as aI,resolve as LA}from"path";import mJ from"process";import{Buffer as Gw}from"buffer";import{createCipheriv as C7,createDecipheriv as Q7,randomBytes as IJ}from"crypto";import{closeSync as VJ,createReadStream as vB,createWriteStream as y7,existsSync as CJ,fsyncSync as cB,openSync as iB,writeFileSync as O7}from"fs";import{access as L7,constants as mB,mkdir as _7,readdir as UA,rename as gB,stat as w1,unlink as WA,writeFile as QJ}from"fs/promises";import{join as Y1}from"path";import y0 from"process";import{pipeline as S7}from"stream/promises";import{createGzip as dB}from"zlib";import A1 from"process";import P$ from"process";import{Buffer as k$}from"buffer";import{createCipheriv as Z7,createDecipheriv as h7,randomBytes as yJ}from"crypto";import{closeSync as OJ,createReadStream as lB,createWriteStream as D7,existsSync as BA,fsyncSync as nB,openSync as pB,writeFileSync as k7}from"fs";import{access as x7,constants as rB,mkdir as P7,readdir as jA,rename as tB,stat as X1,unlink as zA,writeFile as LJ}from"fs/promises";import{isAbsolute as b7,join as J1,resolve as u7}from"path";import D from"process";import{pipeline as v7}from"stream/promises";import{createGzip as aB}from"zlib";import U1 from"process";import b$ from"process";import GA from"process";import{existsSync as KA}from"fs";import{resolve as _J}from"path";import{existsSync as c7}from"fs";import{existsSync as i7,readdirSync as m7}from"fs";import{extname as SJ,resolve as sB}from"path";import g7 from"process";import{join as d7,relative as l7,resolve as oB}from"path";import _A from"process";import{Buffer as x$}from"buffer";import{createCipheriv as n7,createDecipheriv as p7,randomBytes as ZJ}from"crypto";import{closeSync as hJ,createReadStream as eB,createWriteStream as r7,existsSync as FA,fsyncSync as $j,openSync as wj,writeFileSync as t7}from"fs";import{access as a7,constants as Yj,mkdir as s7,readdir as NA,rename as Aj,stat as W1,unlink as qA,writeFile as DJ}from"fs/promises";import{isAbsolute as o7,join as B1,resolve as e7}from"path";import k from"process";import{pipeline as $F}from"stream/promises";import{createGzip as Xj}from"zlib";import j1 from"process";import u$ from"process";import TA from"process";import{existsSync as fA}from"fs";import{resolve as vJ}from"path";import{existsSync as RN}from"fs";class fj{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!hB($))return!0;return DB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=hB(Y)?DB(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Hj{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function AF($,w){this[$]=YF.bind(null,w)}class $U{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!kB($))return!0;return xB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=kB(Y)?xB(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class wU{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function UF($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function WF($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function BF($){return $.getStats().size*2}function YU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let A=[...w];for(let X of $)if($0(X)&&"name"in X){if(!A.find((U)=>$0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if($0(X)&&"path"in X){if(!A.find((U)=>$0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>SA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!$0(w)||!$0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=YU(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&$0(X[0])&&$0(Y[A][0])){let J=[...X];for(let U of Y[A])if($0(U)&&"name"in U){if(!J.find((W)=>$0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if($0(U)&&"path"in U){if(!J.find((W)=>$0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>SA(B,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function SA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!SA($[Y],w[Y]))return!1;return!0}if($0($)&&$0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!SA($[X],w[X]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function jF($,w){if(!Mj($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return YU(w,A)}catch{return null}}catch{return null}}async function zF({name:$="",cwd:w,defaultConfig:Y}){let A=w||mJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=LA(A,`${U}${B}`),j=await jF(W,Y);if(j!==null)return j}try{let U=LA(A,"package.json");if(Mj(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return YU(Y,W)}catch{}}}catch{}return Y}function GF($,w={}){let Y=OA.cwd();while(Y.includes("storage"))Y=uB(Y,"..");let A=uB(Y,$||"");if(w?.relative)return V7(OA.cwd(),A);return A}async function KF(){try{let $=await zF({name:"clarity",defaultConfig:MA,cwd:OA.cwd(),endpoint:"",headers:{}});return{...MA,...$}}catch{return MA}}function U0(){if(P$.env.NODE_ENV==="test"||P$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function FF(){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 Vj{async format($){let w=await FF(),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:A1.pid,hostname:w(),environment:A1.env.NODE_ENV||"development",platform:A1.platform,version:A1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:A1.env.NODE_ENV||A1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ZA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...dJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Vj,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??y0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...IA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...IA};return{...IA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:dJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await L7(this.config.logDirectory,mB.F_OK|mB.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await _7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Gw.from($);try{if(!CJ(this.currentLogFile))await QJ(this.currentLogFile,"",{mode:420});if(X=iB(this.currentLogFile,"a",420),O7(X,W,{flag:"a"}),cB(X),X!==void 0)VJ(X),X=void 0;if((await w1(this.currentLogFile)).size===0){if(await QJ(this.currentLogFile,W,{flag:"w",mode:420}),(await w1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{VJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Y1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Y1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Y1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return IJ(16).toString("hex")}generateKey(){return IJ(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=IJ(16),A=C7("aes-256-gcm",w,Y),X=Gw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Gw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=dB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Gw.from(Gw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await w1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await UA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await w1(Y).catch(()=>null))try{if(await gB(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await WA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await QJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await w1(Y).catch(()=>null))await gB(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await UA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await WA(Y1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=vB($),A=y7(w),X=dB();await S7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),CJ(this.currentLogFile))try{let $=iB(this.currentLogFile,"r+");cB($),VJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await UA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await WA(Y1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=y0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${a.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!U0()){let j=Dj[$],z=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
|
|
5
|
-
`);for(let
|
|
6
|
-
`;if(
|
|
7
|
-
`;
|
|
8
|
-
`,
|
|
9
|
-
`),U=Math.max(...J.map((
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!y0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await UA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=Y1(this.config.logDirectory,A);if($.before)try{if((await w1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await WA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function RA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let A=[...w];for(let X of $)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>hA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!d(w)||!d($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=RA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&d(X[0])&&d(Y[A][0])){let J=[...X];for(let U of Y[A])if(d(U)&&"name"in U){if(!J.find((W)=>d(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((W)=>d(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>hA(B,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function AU($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:RA($,w);if(Array.isArray($))return Y==="replace"?w:RA($,w);if(!d(w)||!d($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=RA(U,J);else if(d(J)&&d(U))A[X]=AU(U,J,Y);else A[X]=J}return A}function hA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!hA($[Y],w[Y]))return!1;return!0}if(d($)&&d(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!hA($[X],w[X]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function EA($,w,Y="replace"){if(!Rj($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return AU(w,X,Y)}catch{return null}}catch{return null}}function NF($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)L0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=KY.env[F]||KY.env[T];if(q!==void 0){if(Y)L0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((H)=>H.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function qF({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?NF($,X,J):X,j=Y||KY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)L0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,c0(j,"config"),c0(j,".config"),A?c0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)L0.info(`Searching for configuration in: ${E}`);let M=[c0(j,"config"),c0(j,".config")].concat(A?[c0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let y of M)for(let C of z){let f=c0(E,`${y}${C}`),I=await EA(f,W,B);if(I!==null){if(J)L0.success(`Configuration loaded from: ${f}`);return I}}}if($){let E=c0(MJ(),".config",$),H=["config",`${$}.config`];if(w)H.push(`${w}.config`);if(J)L0.info(`Checking user config directory: ${E}`);for(let M of H)for(let y of z){let C=c0(E,`${M}${y}`),f=await EA(C,W,B);if(f!==null){if(J)L0.success(`Configuration loaded from user config directory: ${C}`);return f}}}if($){let E=c0(MJ(),".config"),H=[`.${$}.config`];if(w)H.push(`.${w}.config`);if(J)L0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of H)for(let y of z){let C=c0(E,`${M}${y}`),f=await EA(C,W,B);if(f!==null){if(J)L0.success(`Configuration loaded from user config directory dotfile: ${C}`);return f}}}if($){let E=MJ(),H=[`.${$}.config`,`.${$}`];if(w)H.push(`.${w}.config`),H.push(`.${w}`);if(J)L0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of H)for(let y of z){let C=c0(E,`${M}${y}`),f=await EA(C,W,B);if(f!==null){if(J)L0.success(`Configuration loaded from user home directory: ${C}`);return f}}}try{let E=c0(j,"package.json");if(Rj(E)){let H=await import(E),M=H[$];if(!M&&w){if(M=H[w],M&&J)L0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)L0.success(`Configuration loaded from package.json: ${M===H[$]?$:w}`);return AU(W,M,B)}catch(y){if(J)L0.warn("Failed to merge package.json config:",y)}}}catch(E){if(J)L0.warn("Failed to load package.json:",E)}if(J)L0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function EF($,w={}){let Y=yA.cwd();while(Y.includes("storage"))Y=bB(Y,"..");let A=bB(Y,$||"");if(w?.relative)return M7(yA.cwd(),A);return A}async function TF(){try{let $=await qF({name:"clarity",alias:"logging",defaultConfig:VA,cwd:yA.cwd()});return{...VA,...$||{}}}catch{return VA}}function F0(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fF(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b$<"u"){let $=b$.type;if($==="renderer"||$==="worker")return!1;return!!(b$.versions&&(b$.versions.node||b$.versions.bun))}return!1}class Cj{async format($){let w=await fF(),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: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 DA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...lJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Cj,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...CA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...CA};return{...CA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:lJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await x7(this.config.logDirectory,rB.F_OK|rB.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await P7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k$.from($);try{if(!BA(this.currentLogFile))await LJ(this.currentLogFile,"",{mode:420});if(X=pB(this.currentLogFile,"a",420),k7(X,W,{flag:"a"}),nB(X),X!==void 0)OJ(X),X=void 0;if((await X1(this.currentLogFile)).size===0){if(await LJ(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{OJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return yJ(16).toString("hex")}generateKey(){return yJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=yJ(16),A=Z7("aes-256-gcm",w,Y),X=k$.isBuffer($)?$:k$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=k$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=aB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(k$.from(k$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let $=await X1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await jA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await X1(Y).catch(()=>null))try{if(await tB(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await zA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await LJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await X1(Y).catch(()=>null))await tB(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await jA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await zA(J1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=lB($),A=D7(w),X=aB();await v7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),BA(this.currentLogFile))try{let $=pB(this.currentLogFile,"r+");nB($),OJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await jA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await zA(J1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=D.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${u.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),w}supportsHyperlinks(){if(F0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=D.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(b7(w)||w.startsWith("./")||w.startsWith("../"))w=u7(w);else return null;return BA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":kj[$],K=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:u.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:u.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
|
|
13
|
-
`);for(let q of
|
|
14
|
-
`;if(
|
|
15
|
-
`;if(
|
|
16
|
-
`);if(this[
|
|
17
|
-
`,
|
|
18
|
-
`),
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
21
|
-
`)}finishProgressBar(
|
|
4
|
+
import{createRequire as F6}from"node:module";var z6=Object.defineProperty;var G6=(w)=>w;function K6(w,$){this[w]=G6.bind(null,$)}var EB=(w,$)=>{for(var Y in $)z6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:K6.bind($,Y)})};var t=(w,$)=>()=>(w&&($=w(w=0)),$);var b=F6(import.meta.url);import{existsSync as hB,statSync as DB}from"fs";import{existsSync as fK,mkdirSync as y4,readdirSync as O4,readFileSync as HK,writeFileSync as L4}from"fs";import{homedir as w1}from"os";import{dirname as Z4,resolve as Xw}from"path";import mA from"process";import{existsSync as xB,statSync as PB}from"fs";import{existsSync as lJ,mkdirSync as RK,readdirSync as MK,writeFileSync as IK}from"fs";import{homedir as $1}from"os";import{dirname as bB,resolve as i0}from"path";import b$ from"process";import{join as VK,relative as CK,resolve as uB}from"path";import _A from"process";import{existsSync as Rj,mkdirSync as i4,readdirSync as m4,writeFileSync as g4}from"fs";import{homedir as CJ}from"os";import{dirname as n4,resolve as v0}from"path";import FY from"process";import{join as yK,relative as OK,resolve as cB}from"path";import SA from"process";import{existsSync as Mj,mkdirSync as s4,readdirSync as o4,writeFileSync as e4}from"fs";import{dirname as $I,resolve as ZA}from"path";import nJ from"process";import{Buffer as q$}from"buffer";import{createCipheriv as LK,createDecipheriv as _K,randomBytes as yJ}from"crypto";import{closeSync as OJ,createReadStream as vB,createWriteStream as SK,existsSync as LJ,fsyncSync as iB,openSync as mB,writeFileSync as ZK}from"fs";import{access as kK,constants as gB,mkdir as hK,readdir as BA,rename as dB,stat as Y1,unlink as jA,writeFile as _J}from"fs/promises";import{join as A1}from"path";import O0 from"process";import{pipeline as DK}from"stream/promises";import{createGzip as lB}from"zlib";import X1 from"process";import iw from"process";import{Buffer as cw}from"buffer";import{createCipheriv as xK,createDecipheriv as PK,randomBytes as SJ}from"crypto";import{closeSync as ZJ,createReadStream as nB,createWriteStream as bK,existsSync as zA,fsyncSync as pB,openSync as rB,writeFileSync as uK}from"fs";import{access as cK,constants as tB,mkdir as vK,readdir as GA,rename as aB,stat as J1,unlink as KA,writeFile as kJ}from"fs/promises";import{isAbsolute as iK,join as U1,resolve as mK}from"path";import h from"process";import{pipeline as gK}from"stream/promises";import{createGzip as sB}from"zlib";import Q1 from"process";import mw from"process";import FA from"process";import{existsSync as qA}from"fs";import{resolve as hJ}from"path";import{existsSync as dK}from"fs";import{existsSync as lK,readdirSync as nK}from"fs";import{extname as DJ,resolve as oB}from"path";import pK from"process";import{join as rK,relative as tK,resolve as eB}from"path";import kA from"process";import{Buffer as vw}from"buffer";import{createCipheriv as aK,createDecipheriv as sK,randomBytes as xJ}from"crypto";import{closeSync as PJ,createReadStream as wj,createWriteStream as oK,existsSync as NA,fsyncSync as $j,openSync as Yj,writeFileSync as eK}from"fs";import{access as w7,constants as Aj,mkdir as $7,readdir as EA,rename as Xj,stat as W1,unlink as TA,writeFile as bJ}from"fs/promises";import{isAbsolute as Y7,join as B1,resolve as A7}from"path";import D from"process";import{pipeline as X7}from"stream/promises";import{createGzip as Jj}from"zlib";import j1 from"process";import gw from"process";import HA from"process";import{existsSync as RA}from"fs";import{resolve as gJ}from"path";import{existsSync as VF}from"fs";class fj{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!hB(w))return!0;return DB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=hB(Y)?DB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Hj{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function Q7(w,$){this[w]=U7.bind(null,$)}class XU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!xB(w))return!0;return PB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=xB(Y)?PB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class JU{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function j7(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function z7(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function G7(w){return w.getStats().size*2}function UU(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&w0($[0])&&"id"in $[0]&&$[0].id===3&&w0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(w0($)&&w0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(w0(w)&&"arr"in w&&Array.isArray(w.arr)&&w0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&w0($[0])&&w0(w[0])){let A=[...$];for(let X of w)if(w0(X)&&"name"in X){if(!A.find((U)=>w0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((U)=>w0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>hA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!w0($)||!w0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=UU(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&w0(X[0])&&w0(Y[A][0])){let J=[...X];for(let U of Y[A])if(w0(U)&&"name"in U){if(!J.find((Q)=>w0(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((Q)=>w0(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>hA(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function hA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!hA(w[Y],$[Y]))return!1;return!0}if(w0(w)&&w0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!hA(w[X],$[X]))return!1}return!0}return!1}function w0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function K7(w,$){if(!Mj(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return UU($,A)}catch{return null}}catch{return null}}async function F7({name:w="",cwd:$,defaultConfig:Y}){let A=$||nJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=ZA(A,`${U}${W}`),B=await K7(Q,Y);if(B!==null)return B}try{let U=ZA(A,"package.json");if(Mj(U)){let Q=(await import(U))[w];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return UU(Y,Q)}catch{}}}catch{}return Y}function q7(w,$={}){let Y=SA.cwd();while(Y.includes("storage"))Y=cB(Y,"..");let A=cB(Y,w||"");if($?.relative)return OK(SA.cwd(),A);return A}async function N7(){try{let w=await F7({name:"clarity",defaultConfig:VA,cwd:SA.cwd(),endpoint:"",headers:{}});return{...VA,...w}}catch{return VA}}function U0(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E7(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof iw<"u"){let w=iw.type;if(w==="renderer"||w==="worker")return!1;return!!(iw.versions&&(iw.versions.node||iw.versions.bun))}return!1}class Vj{async format(w){let $=await E7(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:X1.pid,hostname:$(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class DA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...rJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Vj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...CA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...CA};return{...CA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:rJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await kK(this.config.logDirectory,gB.F_OK|gB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await hK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:q$.from(w);try{if(!LJ(this.currentLogFile))await _J(this.currentLogFile,"",{mode:420});if(X=mB(this.currentLogFile,"a",420),ZK(X,Q,{flag:"a"}),iB(X),X!==void 0)OJ(X),X=void 0;if((await Y1(this.currentLogFile)).size===0){if(await _J(this.currentLogFile,Q,{flag:"w",mode:420}),(await Y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{OJ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 w=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return yJ(16).toString("hex")}generateKey(){return yJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=yJ(16),A=LK("aes-256-gcm",$,Y),X=q$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:q$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=lB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(q$.from(q$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await Y1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await BA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await Y1(Y).catch(()=>null))try{if(await dB(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await jA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await _J(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await Y1(Y).catch(()=>null))await dB(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await BA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await jA(A1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=vB(w),A=SK($),X=lB();await DK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),LJ(this.currentLogFile))try{let w=mB(this.currentLogFile,"r+");iB(w),OJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await BA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await jA(A1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?a.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=O0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${a.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let B=Dj[w],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
|
|
5
|
+
`);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:a.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
|
|
6
|
+
`;if(W)Q+=`${W}
|
|
7
|
+
`;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:a.blue("◐"),tag:Y,message:`${a.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
8
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!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}${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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new DA($,{...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(!LJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return vB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=q$.isBuffer(w)?w:q$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=_K("aes-256-gcm",Y,X);return W.setAuthTag(J),q$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!U0()){let J=w.split(`
|
|
9
|
+
`),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(Q),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(U0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${a.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();O0.stdin.removeListener("data",Y);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",W=a.blue("◐");console.error(`${W} ${U} ${a.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||U0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),W!==void 0)this.activeProgressBar.message=W;let Q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Q)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||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;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||U0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=a.green("━".repeat(A)),U=a.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?a.green("✓"):a.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=O0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,O0.stdout.write(w.lastRenderedLine),$)O0.stdout.write(`
|
|
12
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await BA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=A1(this.config.logDirectory,A);if(w.before)try{if((await Y1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await jA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function IA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&d($[0])&&"id"in $[0]&&$[0].id===3&&d($[1])&&"id"in $[1]&&$[1].id===4)return $;if(d($)&&d(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(d(w)&&"arr"in w&&Array.isArray(w.arr)&&d($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&d($[0])&&d(w[0])){let A=[...$];for(let X of w)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>xA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!d($)||!d(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=IA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&d(X[0])&&d(Y[A][0])){let J=[...X];for(let U of Y[A])if(d(U)&&"name"in U){if(!J.find((Q)=>d(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((Q)=>d(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>xA(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function QU(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:IA(w,$);if(Array.isArray(w))return Y==="replace"?$:IA(w,$);if(!d($)||!d(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=IA(U,J);else if(d(J)&&d(U))A[X]=QU(U,J,Y);else A[X]=J}return A}function xA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!xA(w[Y],$[Y]))return!1;return!0}if(d(w)&&d($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!xA(w[X],$[X]))return!1}return!0}return!1}function d(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function fA(w,$,Y="replace"){if(!Rj(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return QU($,X,Y)}catch{return null}}catch{return null}}function T7(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)_0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=FY.env[K]||FY.env[E];if(q!==void 0){if(Y)_0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function f7({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?T7(w,X,J):X,B=Y||FY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)_0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,v0(B,"config"),v0(B,".config"),A?v0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)_0.info(`Searching for configuration in: ${N}`);let R=[v0(B,"config"),v0(B,".config")].concat(A?[v0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let y of R)for(let V of j){let T=v0(N,`${y}${V}`),M=await fA(T,Q,W);if(M!==null){if(J)_0.success(`Configuration loaded from: ${T}`);return M}}}if(w){let N=v0(CJ(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)_0.info(`Checking user config directory: ${N}`);for(let R of f)for(let y of j){let V=v0(N,`${R}${y}`),T=await fA(V,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user config directory: ${V}`);return T}}}if(w){let N=v0(CJ(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)_0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let y of j){let V=v0(N,`${R}${y}`),T=await fA(V,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user config directory dotfile: ${V}`);return T}}}if(w){let N=CJ(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)_0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let y of j){let V=v0(N,`${R}${y}`),T=await fA(V,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user home directory: ${V}`);return T}}}try{let N=v0(B,"package.json");if(Rj(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)_0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)_0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return QU(Q,R,W)}catch(y){if(J)_0.warn("Failed to merge package.json config:",y)}}}catch(N){if(J)_0.warn("Failed to load package.json:",N)}if(J)_0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function H7(w,$={}){let Y=_A.cwd();while(Y.includes("storage"))Y=uB(Y,"..");let A=uB(Y,w||"");if($?.relative)return CK(_A.cwd(),A);return A}async function R7(){try{let w=await f7({name:"clarity",alias:"logging",defaultConfig:yA,cwd:_A.cwd()});return{...yA,...w||{}}}catch{return yA}}function F0(){if(mw.env.NODE_ENV==="test"||mw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function M7(){if(mw.env.NODE_ENV==="test"||mw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof mw<"u"){let w=mw.type;if(w==="renderer"||w==="worker")return!1;return!!(mw.versions&&(mw.versions.node||mw.versions.bun))}return!1}class Cj{async format(w){let $=await M7(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:Q1.pid,hostname:$(),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 PA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...tJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Cj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??h.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...OA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...OA};return{...OA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:tJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await cK(this.config.logDirectory,tB.F_OK|tB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await vK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:cw.from(w);try{if(!zA(this.currentLogFile))await kJ(this.currentLogFile,"",{mode:420});if(X=rB(this.currentLogFile,"a",420),uK(X,Q,{flag:"a"}),pB(X),X!==void 0)ZJ(X),X=void 0;if((await J1(this.currentLogFile)).size===0){if(await kJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await J1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{ZJ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 w=new Date().toISOString().split("T")[0];return U1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return SJ(16).toString("hex")}generateKey(){return SJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=SJ(16),A=xK("aes-256-gcm",$,Y),X=cw.isBuffer(w)?w:cw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=cw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=sB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(cw.from(cw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let w=await J1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await GA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await J1(Y).catch(()=>null))try{if(await aB(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await KA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await kJ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await J1(Y).catch(()=>null))await aB(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await GA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await KA(U1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=nB(w),A=bK($),X=sB();await gK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),zA(this.currentLogFile))try{let w=rB(this.currentLogFile,"r+");pB(w),ZJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await GA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await KA(U1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let w=typeof h.env.NO_COLOR<"u",$=h.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof h.stderr<"u"&&h.stderr.isTTY||typeof h.stdout<"u"&&h.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=h.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${u.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(F0())return!1;let w=h.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=h.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(iK($)||$.startsWith("./")||$.startsWith("../"))$=mK($);else return null;return zA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":xj[w],G=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:u.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:u.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
|
|
13
|
+
`);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!F0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
|
|
14
|
+
`;if(W)j+=`${W}
|
|
15
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&h.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!F0()&&h.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!F0()&&h.stdout.isTTY)h.stdout.write(`
|
|
16
|
+
`);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&h.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
17
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":u.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new PA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(F0())throw Error("createReadStream is not supported in browser environments");if(!zA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return nB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=cw.isBuffer(w)?w:cw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=PK("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=cw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F0()}isServerMode(){return!F0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
|
|
18
|
+
`),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1}))}else if(!F0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(F0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();h.stdin.removeListener("data",Y);try{if(typeof h.stdin.setRawMode==="function")h.stdin.setRawMode(!1)}catch{}h.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof h.stdin.setRawMode==="function")h.stdin.setRawMode(!0)}catch{}h.stdin.resume(),h.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${B}${Q} ${u.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!h.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=h.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,h.stdout.write(w.lastRenderedLine),$)h.stdout.write(`
|
|
21
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||F0()||!h.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await GA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=U1(this.config.logDirectory,A);if(w.before)try{if((await J1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await KA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function yj(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Oj(w){return w instanceof o0}function I7(w){return w instanceof bA}function V7(w){if(Oj(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class gA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return EY.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=FA.env[Q]||(B?FA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=FA.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof uA)throw z;throw N$.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw N$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(FA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
22
22
|
|
|
23
|
-
`;for(let A of
|
|
23
|
+
`;for(let A of w)Y+=`${A.key}
|
|
24
24
|
`,Y+=` Type: ${A.type}
|
|
25
25
|
`,Y+=` Description: ${A.description}
|
|
26
26
|
`,Y+=` Example: ${A.example}
|
|
27
27
|
|
|
28
|
-
`;return Y}formatAsMarkdown(
|
|
28
|
+
`;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
|
|
29
29
|
|
|
30
30
|
`;Y+=`| Variable | Type | Description | Example |
|
|
31
31
|
`,Y+=`|----------|------|-------------|----------|
|
|
32
|
-
`;for(let A of
|
|
33
|
-
`;return Y}}function MF($,w){let Y=Zj("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function Oj($,w,Y={}){return Lj($,w,Y,new WeakMap)}function Lj($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return _j($,w,X,A);if(!A$(w)||!A$($))return w;return QF($,w,Y,A)}function _j($,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 IF($,w);case"smart":return VF($,w,A);default:return w}return w}function IF($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>gJ(X,A)))Y.push(A);return Y}function VF($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(A$(w[0])&&A$($[0]))return CF($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function CF($,w,Y){let A=[...w];for(let X of $){if(!A$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>A$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function QF($,w,Y,A){let X=w;if(A$(X)&&A.has(X))return A.get(X);let J={...$};if(A$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(A$(B)&&A$(W))J[U]=Lj(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=_j(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function XU($,w,Y="replace"){return Oj($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function gJ($,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(!gJ($[Y],w[Y]))return!1;return!0}if(A$($)&&A$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!gJ($[X],w[X]))return!1}return!0}return!1}function A$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class iA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=z1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!KA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new FY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new FY($,Error("Configuration must export a valid object"),"unknown");let E={config:XU(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)z1.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?Kw.configLoad($,j):Kw.configLoad($,Error(String(j)))}};if(U)return qY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(_J(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return Qj(async()=>{return KA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!KA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=_J($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=_J($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!KA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class JU{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await qY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!c7(w))throw new NY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new NY(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],X=[];return this.validateObjectAgainstSchema($,w,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema($,w,Y,A,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Pj},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UU{fileLoader=new iA;envProcessor=new cA;validator=new JU;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)G$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw G$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||kw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(i0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Kw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?GY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)G$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)G$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?GY($,Y,X):Y,B=[i0($1(),".config",$),i0($1(),".config"),$1()];for(let W of B){if(X)G$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)G$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?GY($,A,J):A;try{let W=i0(Y,"package.json");if(!iJ(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)G$.success(`Configuration loaded from package.json: ${G}`);return{config:XU(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)G$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:GY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Kw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return z1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);z1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,i0($,"config"),i0($,".config"),w?i0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(i0(Y,"package.json")),X}getLocalSearchPaths($,w,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[i0($1(),".config",$),i0($1(),".config"),$1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function Jj($){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 yF($){return v$.loadConfig({...$,__strictErrorHandling:!0})}async function Sj($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await v$.loadConfig($);else A=await v$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)G$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await v$.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function OF($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await v$.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"&&Jj(Y)))return(await v$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await v$.loadConfig({...$,cwd:$.cwd||kw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&Jj(w)))return(await v$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function LF($,w,Y="replace"){let A=new iA;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function GY($,w,Y=!1){let A=new cA,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=kw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function _F($){let w=i0(kw.cwd(),$.configDir),Y=i0(kw.cwd(),$.generatedDir),A=i0(Y,"config-types.ts");if(!iJ(PB(A)))T7(PB(A),{recursive:!0,mode:511});let X=iJ(w)?f7(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${XN}
|
|
32
|
+
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
33
|
+
`;return Y}}function C7(w,$){let Y=kj("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function Lj(w,$,Y={}){return _j(w,$,Y,new WeakMap)}function _j(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return Sj(w,$,X,A);if(!Jw($)||!Jw(w))return $;return _7(w,$,Y,A)}function Sj(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return y7(w,$);case"smart":return O7(w,$,A);default:return $}return $}function y7(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>pJ(X,A)))Y.push(A);return Y}function O7(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Jw($[0])&&Jw(w[0]))return L7(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function L7(w,$,Y){let A=[...$];for(let X of w){if(!Jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((B)=>Jw(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function _7(w,$,Y,A){let X=$;if(Jw(X)&&A.has(X))return A.get(X);let J={...w};if(Jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(Jw(W)&&Jw(Q))J[U]=_j(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=Sj(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function WU(w,$,Y="replace"){return Lj(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function pJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!pJ(w[Y],$[Y]))return!1;return!0}if(Jw(w)&&Jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!pJ(w[X],$[X]))return!1}return!0}return!1}function Jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class dA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=Y;if(X){let B=z1.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!qA(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new qY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new qY(w,Error("Configuration must export a valid object"),"unknown");let N={config:WU($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)z1.setWithFileCheck("file",N,w,J);return N}catch(B){throw B instanceof Error?N$.configLoad(w,B):N$.configLoad(w,Error(String(B)))}};if(U)return EY.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(hJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return yj(async()=>{return qA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!qA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=hJ(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=hJ(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!qA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class BU{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await EY.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!dK($))throw new NY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new NY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:bj},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class jU{fileLoader=new dA;envProcessor=new gA;validator=new BU;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)qw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){let Q=Date.now()-$;throw qw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||b$.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(i0(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw N$.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?KY(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)qw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)qw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?KY(w,Y,X):Y,W=[i0($1(),".config",w),i0($1(),".config"),$1()];for(let Q of W){if(X)qw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)qw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?KY(w,A,J):A;try{let Q=i0(Y,"package.json");if(!lJ(Q))return null;let B=await import(Q),j=B[w],z=w;if(!j&&$)j=B[$],z=$;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)qw.success(`Configuration loaded from package.json: ${z}`);return{config:WU(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)qw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:KY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw N$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return z1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);z1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,i0(w,"config"),i0(w,".config"),$?i0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(i0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[i0($1(),".config",w),i0($1(),".config"),$1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Uj(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function S7(w){return dw.loadConfig({...w,__strictErrorHandling:!0})}async function Zj(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await dw.loadConfig(w);else A=await dw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)qw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await dw.applyEnvironmentVariables(W.name||"",$,!0,W.verbose||!1))?.config??$;return $}}async function Z7(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await dw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Uj(Y)))return(await dw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await dw.loadConfig({...w,cwd:w.cwd||b$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Uj($)))return(await dw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function k7(w,$,Y="replace"){let A=new dA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function KY(w,$,Y=!1){let A=new gA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=b$.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function h7(w){let $=i0(b$.cwd(),w.configDir),Y=i0(b$.cwd(),w.generatedDir),A=i0(Y,"config-types.ts");if(!lJ(bB(A)))RK(bB(A),{recursive:!0,mode:511});let X=lJ($)?MK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${WF}
|
|
34
34
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
35
|
-
`;
|
|
36
|
-
${X.map((
|
|
35
|
+
`;IK(A,J,{mode:438})}function D7(w){let $=null,Y=null,A=()=>{if(!Y)Y=Zj(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)qw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let W=X[U];return A(),W},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,W){if(!$)$={...X};return $[U]=W,!0}})}function x7(w){let $=oB(pK.cwd(),w?.configDir||"./config");function Y(){if(!lK($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=nK($).filter((Q)=>X.has(DJ(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),W=new Map;for(let{base:Q,file:B}of U){let j=DJ(B).toLowerCase(),z=W.get(Q);if(!z){W.set(Q,B);continue}let G=DJ(z).toLowerCase();if(J.indexOf(j)<J.indexOf(G))W.set(Q,B)}return Array.from(W.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function A(){let X=Y(),J=X.map((B)=>B.base),U=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",W=X.length?`{
|
|
36
|
+
${X.map((B)=>{let j=oB($,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
38
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
39
|
-
export type ConfigByName = ${
|
|
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:A(),loader:"ts"}})}}}function UN($,w={}){let Y=_A.cwd();while(Y.includes("storage"))Y=oB(Y,"..");let A=oB(Y,$||"");if(w?.relative)return l7(_A.cwd(),A);return A}function q0(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BN(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u$<"u"){let $=u$.type;if($==="renderer"||$==="worker")return!1;return!!(u$.versions&&(u$.versions.node||u$.versions.bun))}return!1}class cj{async format($){let w=await BN(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:j1.pid,hostname:w(),environment:j1.env.NODE_ENV||"development",platform:j1.platform,version:j1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:j1.env.NODE_ENV||j1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new cj,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...uJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...uJ};return{...uJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await a7(this.config.logDirectory,Yj.F_OK|Yj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await s7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x$.from($);try{if(!FA(this.currentLogFile))await DJ(this.currentLogFile,"",{mode:420});if(X=wj(this.currentLogFile,"a",420),t7(X,W,{flag:"a"}),$j(X),X!==void 0)hJ(X),X=void 0;if((await W1(this.currentLogFile)).size===0){if(await DJ(this.currentLogFile,W,{flag:"w",mode:420}),(await W1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{hJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return B1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return B1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return B1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return ZJ(16).toString("hex")}generateKey(){return ZJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=ZJ(16),A=n7("aes-256-gcm",w,Y),X=x$.isBuffer($)?$:x$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=x$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Xj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(x$.from(x$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await W1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await NA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await W1(Y).catch(()=>null))try{if(await Aj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await qA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await DJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await W1(Y).catch(()=>null))await Aj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await NA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await qA(B1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=eB($),A=r7(w),X=Xj();await $F(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),FA(this.currentLogFile))try{let $=wj(this.currentLogFile,"r+");$j($),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(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await NA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await qA(B1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=k.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${i.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=i.underline(i.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),w}supportsHyperlinks(){if(q0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=k.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(o7(w)||w.startsWith("./")||w.startsWith("../"))w=e7(w);else return null;return FA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":FN[$],K=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:i.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:i.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
|
|
43
|
-
`);for(let q of
|
|
44
|
-
`;if(
|
|
45
|
-
`;if(
|
|
46
|
-
`);if(this[
|
|
47
|
-
`,
|
|
48
|
-
`),
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
51
|
-
`)}finishProgressBar(
|
|
42
|
+
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function jF(w,$={}){let Y=kA.cwd();while(Y.includes("storage"))Y=eB(Y,"..");let A=eB(Y,w||"");if($?.relative)return tK(kA.cwd(),A);return A}function N0(){if(gw.env.NODE_ENV==="test"||gw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function GF(){if(gw.env.NODE_ENV==="test"||gw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gw<"u"){let w=gw.type;if(w==="renderer"||w==="worker")return!1;return!!(gw.versions&&(gw.versions.node||gw.versions.bun))}return!1}class ij{async format(w){let $=await GF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:j1.pid,hostname:$(),environment:j1.env.NODE_ENV||"development",platform:j1.platform,version:j1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:j1.env.NODE_ENV||j1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class lA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...cA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new ij,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...mJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...mJ};return{...mJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:cA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await w7(this.config.logDirectory,Aj.F_OK|Aj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await $7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:vw.from(w);try{if(!NA(this.currentLogFile))await bJ(this.currentLogFile,"",{mode:420});if(X=Yj(this.currentLogFile,"a",420),eK(X,Q,{flag:"a"}),$j(X),X!==void 0)PJ(X),X=void 0;if((await W1(this.currentLogFile)).size===0){if(await bJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await W1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{PJ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return B1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return B1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return B1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return xJ(16).toString("hex")}generateKey(){return xJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=xJ(16),A=aK("aes-256-gcm",$,Y),X=vw.isBuffer(w)?w:vw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=vw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Jj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(vw.from(vw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let w=await W1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await EA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await W1(Y).catch(()=>null))try{if(await Xj(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await TA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await bJ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await W1(Y).catch(()=>null))await Xj(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await EA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await TA(B1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=wj(w),A=oK($),X=Jj();await X7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),NA(this.currentLogFile))try{let w=Yj(this.currentLogFile,"r+");$j(w),PJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await EA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await TA(B1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?i.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let w=typeof D.env.NO_COLOR<"u",$=D.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=D.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${i.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=i.underline(i.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),$}supportsHyperlinks(){if(N0())return!1;let w=D.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=D.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(Y7($)||$.startsWith("./")||$.startsWith("../"))$=A7($);else return null;return NA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":EF[w],G=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:i.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:i.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
|
|
43
|
+
`);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:i.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
|
|
44
|
+
`;if(W)j+=`${W}
|
|
45
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!N0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!N0()&&D.stdout.isTTY)D.stdout.write(`
|
|
46
|
+
`);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:Y,message:`${i.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
47
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":i.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!N0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new lA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!NA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wj(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=vw.isBuffer(w)?w:vw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=sK("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=vw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
|
|
48
|
+
`),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:i.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(j),showTimestamp:!1}))}else if(!N0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${i.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();D.stdin.removeListener("data",Y);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${B}${Q} ${i.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=i.green("━".repeat(A)),U=i.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?i.green("✓"):i.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=D.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,D.stdout.write(w.lastRenderedLine),$)D.stdout.write(`
|
|
51
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||N0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await EA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=B1(this.config.logDirectory,A);if(w.before)try{if((await W1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await TA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function TF(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class GU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return AU.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=HA.env[Q]||(B?HA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=HA.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof zU)throw z;throw G1.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw G1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(HA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
52
52
|
|
|
53
|
-
`;for(let A of
|
|
53
|
+
`;for(let A of w)Y+=`${A.key}
|
|
54
54
|
`,Y+=` Type: ${A.type}
|
|
55
55
|
`,Y+=` Description: ${A.description}
|
|
56
56
|
`,Y+=` Example: ${A.example}
|
|
57
57
|
|
|
58
|
-
`;return Y}formatAsMarkdown(
|
|
58
|
+
`;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
|
|
59
59
|
|
|
60
60
|
`;Y+=`| Variable | Type | Description | Example |
|
|
61
61
|
`,Y+=`|----------|------|-------------|----------|
|
|
62
|
-
`;for(let A of
|
|
63
|
-
`;return Y}}function qN($,w,Y={}){return rj($,w,Y,new WeakMap)}function rj($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return tj($,w,X,A);if(!X$(w)||!X$($))return w;return HN($,w,Y,A)}function tj($,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 EN($,w);case"smart":return TN($,w,A);default:return w}return w}function EN($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>oJ(X,A)))Y.push(A);return Y}function TN($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(X$(w[0])&&X$($[0]))return fN($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function fN($,w,Y){let A=[...w];for(let X of $){if(!X$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>X$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function HN($,w,Y,A){let X=w;if(X$(X)&&A.has(X))return A.get(X);let J={...$};if(X$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(X$(B)&&X$(W))J[U]=rj(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=tj(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function aj($,w,Y="replace"){return qN($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function oJ($,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(!oJ($[Y],w[Y]))return!1;return!0}if(X$($)&&X$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!oJ($[X],w[X]))return!1}return!0}return!1}function X$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class sj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=QA.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!fA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new bA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new bA($,Error("Configuration must export a valid object"),"unknown");let E={config:aj(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)QA.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?G1.configLoad($,j):G1.configLoad($,Error(String(j)))}};if(U)return eJ.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(vJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return NN(async()=>{return fA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!fA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=vJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=vJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!fA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class oj{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await eJ.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!RN(w))throw new uA(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new uA(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],X=[];return this.validateObjectAgainstSchema($,w,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema($,w,Y,A,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:MN},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function IN($){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 ej{fileLoader=new sj;envProcessor=new BU;validator=new oj;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)V$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw V$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||vA.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(Y$(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw G1.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${IN(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?HA($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)V$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)V$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?HA($,Y,X):Y,B=[Y$(ew(),".config",$),Y$(ew(),".config"),ew()];for(let W of B){if(X)V$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)V$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?HA($,A,J):A;try{let W=Y$(Y,"package.json");if(!q7(W))return null;let j={};try{j=JSON.parse(E7(W,"utf8"))}catch(K){if(J)V$.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let z=j[$],G=$;if(!z&&w){let K=Array.isArray(w)?w:[w];for(let F of K){if(!F)continue;if(j[F]){z=j[F],G=F;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)V$.success(`Configuration loaded from package.json: ${G}`);return{config:aj(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)V$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:HA($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw G1.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return QA.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);QA.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Y$($,"config"),Y$($,".config"),w?Y$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(Y$(Y,"package.json")),X}getLocalSearchPaths($,w,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[Y$(ew(),".config",$),Y$(ew(),".config"),ew()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}async function jU($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await cJ.loadConfig($);else A=await cJ.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)V$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await cJ.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}function HA($,w,Y=!1){let A=new BU,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=vA.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}var QA,eJ,wF,YF=($)=>$,XF=($,w)=>{for(var Y in w)wF($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:AF.bind(w,Y)})},JF=($,w)=>()=>($&&(w=$($=0)),w),Ij,Zj,z1,qY,hj,hF,DF,Uj,MA,dJ,O0,a,kF,Wj,xF,Bj,PF,bF,kJ,uF,jj,zj,xJ,vF,cF,iF,mF,IA,Dj,gF,L0,dF,lF,Gj,VA,lJ,N0,u,nF,Kj,pF,Fj,rF,tF,PJ,aF,Nj,qj,sF,bJ,oF,eF,$N,wN,YN,CA,kj,AN,XN="0.15.6",a0,kA,FY,nJ,pJ,xA,rJ,tJ,NY,aJ,sJ,Kw,xj,Pj,G$,v$,bj,uj,JN,WN,vj,PA,bV,I0,i,uV,jN,vV,zN,cV,iV,Ej,mV,GN,KN,gV,Tj,dV,lV,nV,pV,rV,uJ,FN,tV,K$,ij,bA,mj,gj,WU,dj,lj,uA,nj,pj,G1,MN,V$,cJ,$3,w3;var zU=t(()=>{QA=new fj,eJ=new Hj,wF=Object.defineProperty;Ij={};XF(Ij,{withErrorRecovery:()=>Qj,tryLoadConfig:()=>LF,loadConfigWithResult:()=>yF,loadConfig:()=>Sj,isRetryableError:()=>RF,isConfigNotFoundError:()=>HF,isBunfigError:()=>yj,globalPerformanceMonitor:()=>qY,globalCache:()=>z1,getEnvOrDefault:()=>MF,generateConfigTypes:()=>_F,defaultGeneratedDir:()=>uj,defaultConfigDir:()=>bj,deepMergeWithArrayStrategy:()=>XU,deepMerge:()=>Oj,createLibraryConfig:()=>SF,config:()=>OF,bunfigPlugin:()=>ZF,applyEnvVarsToConfig:()=>GY,TypeGenerationError:()=>tJ,SchemaValidationError:()=>NY,PluginError:()=>sJ,PerformanceMonitor:()=>wU,FileSystemError:()=>rJ,ErrorFactory:()=>Kw,EnvVarError:()=>xA,EnvProcessor:()=>cA,ConfigValidator:()=>JU,ConfigValidationError:()=>nJ,ConfigNotFoundError:()=>kA,ConfigMergeError:()=>pJ,ConfigLoader:()=>UU,ConfigLoadError:()=>FY,ConfigFileLoader:()=>iA,ConfigCache:()=>$U,CacheUtils:()=>hj,BunfigError:()=>a0,BrowserConfigError:()=>aJ,ArrayMergeStrategies:()=>xj});JN=JF(async()=>{Zj=import.meta.require,z1=new $U,qY=new wU,hj={createKey:UF,isEquivalent:WF,estimateMemoryUsage:BF},hF=LA(mJ.cwd(),"config"),DF=LA(mJ.cwd(),"src/generated"),Uj=OA.env.CLARITY_LOG_DIR||I7(GF(),"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},dJ=await KF(),O0={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=O0,kF=O0.red,Wj=O0.green,xF=O0.yellow,Bj=O0.blue,PF=O0.magenta,bF=O0.cyan,kJ=O0.white,uF=O0.gray,jj=O0.bgRed,zj=O0.bgYellow,xJ=O0.bold,vF=O0.dim,cF=O0.italic,iF=O0.underline,mF=O0.reset,IA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Dj={debug:"\uD83D\uDD0D",info:Bj("ℹ"),success:Wj("✓"),warning:zj(kJ(xJ(" WARN "))),error:jj(kJ(xJ(" ERROR ")))},gF=new ZA("stacks"),L0=new ZA("bunfig",{showTags:!0}),dF=c0(KY.cwd(),"config"),lF=c0(KY.cwd(),"src/generated"),Gj=yA.env.CLARITY_LOG_DIR||R7(EF(),"logs"),VA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},lJ=await TF(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=N0,nF=N0.red,Kj=N0.green,pF=N0.yellow,Fj=N0.blue,rF=N0.magenta,tF=N0.cyan,PJ=N0.white,aF=N0.gray,Nj=N0.bgRed,qj=N0.bgYellow,sF=N0.bgGray,bJ=N0.bold,oF=N0.dim,eF=N0.italic,$N=N0.underline,wN=N0.strikethrough,YN=N0.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kj={debug:"\uD83D\uDD0D",info:Fj("ℹ"),success:Kj("✓"),warning:qj(PJ(bJ(" WARN "))),error:Nj(PJ(bJ(" ERROR ")))},AN=new DA("stacks"),a0=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},kA=class extends a0{code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},FY=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}},nJ=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})}},pJ=class extends a0{code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},xA=class extends a0{code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},rJ=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}},tJ=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}},NY=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})}},aJ=class extends a0{code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},sJ=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}},Kw={configNotFound($,w,Y){return new kA($,w,Y)},configLoad($,w,Y){return new FY($,w,Y)},configValidation($,w,Y){return new nJ($,w,Y)},configMerge($,w,Y,A){return new pJ($,w,Y,A)},envVar($,w,Y,A){return new xA($,w,Y,A)},fileSystem($,w,Y){return new rJ($,w,Y)},typeGeneration($,w,Y){return new tJ($,w,Y)},schemaValidation($,w,Y){return new NY($,w,Y)},browserConfig($,w,Y,A){return new aJ($,w,Y,A)},plugin($,w,Y){return new sJ($,w,Y)}},xj={replace:"replace",concat:"concat",smart:"smart"},Pj=/^https?:\/\//,G$=new DA("bunfig",{showTags:!0}),v$=new UU,bj=i0(kw.cwd(),"config"),uj=i0(kw.cwd(),"src/generated")});WN=_A.env.CLARITY_LOG_DIR||d7(UN(),"logs"),vj={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:WN,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PA={...vj},bV=(async()=>{try{let{loadConfig:$}=await JN().then(()=>Ij),w=await $({name:"clarity",alias:"logging",defaultConfig:vj,cwd:_A.cwd()});if(w)Object.assign(PA,w)}catch{}return PA})();I0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=I0,uV=I0.red,jN=I0.green,vV=I0.yellow,zN=I0.blue,cV=I0.magenta,iV=I0.cyan,Ej=I0.white,mV=I0.gray,GN=I0.bgRed,KN=I0.bgYellow,gV=I0.bgGray,Tj=I0.bold,dV=I0.dim,lV=I0.italic,nV=I0.underline,pV=I0.strikethrough,rV=I0.reset,uJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},FN={debug:"\uD83D\uDD0D",info:zN("ℹ"),success:jN("✓"),warning:KN(Ej(Tj(" WARN "))),error:GN(Ej(Tj(" ERROR ")))};tV=new mA("stacks");K$=class K$ 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}${$}`}};ij=class ij extends K${code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};bA=class bA extends K${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}};mj=class mj extends K${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};gj=class gj extends K${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}};WU=class WU extends K${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})}};dj=class dj extends K${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}};lj=class lj extends K${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};uA=class uA extends K${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};nj=class nj extends K${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};pj=class pj extends K${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}};G1={configNotFound($,w,Y){return new ij($,w,Y)},configLoad($,w,Y){return new bA($,w,Y)},configValidation($,w,Y){return new mj($,w,Y)},configMerge($,w,Y,A){return new gj($,w,Y,A)},envVar($,w,Y,A){return new WU($,w,Y,A)},fileSystem($,w,Y){return new dj($,w,Y)},typeGeneration($,w,Y){return new lj($,w,Y)},schemaValidation($,w,Y){return new uA($,w,Y)},browserConfig($,w,Y,A){return new nj($,w,Y,A)},plugin($,w,Y){return new pj($,w,Y)}};MN=/^https?:\/\//;V$=new mA("bunfig",{showTags:!0});cJ=new ej;$3=Y$(vA.cwd(),"config"),w3=Y$(vA.cwd(),"src/generated")});function F1($){return $.startsWith("*.")}function EY($,w){if(!F1(w))return!1;let Y=w.slice(1);return $.length>Y.length&&$.endsWith(Y)}function gA($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!F1(J))continue;if(EY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}var R;var c$=t(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as bN}from"node:module";import{Resolver as EU}from"node:dns/promises";import{createHash as vN,sign as cN}from"node:crypto";import{createHash as iN}from"node:crypto";import{sign as mN}from"node:crypto";import{generateKeyPairSync as G2,X509Certificate as sN}from"node:crypto";import TU from"node:os";import fU from"node:path";import{existsSync as Bz,statSync as jz}from"fs";import{existsSync as eN,mkdirSync as C3,readdirSync as Q3,readFileSync as $q,writeFileSync as y3}from"fs";import{homedir as q1}from"os";import{dirname as _3,resolve as U$}from"path";import SX from"process";import{existsSync as zz,statSync as Gz}from"fs";import{existsSync as mU,mkdirSync as wq,readdirSync as Yq,writeFileSync as Aq}from"fs";import{homedir as E1}from"os";import{dirname as Kz,resolve as g0}from"path";import bw from"process";import{join as Xq,relative as Jq,resolve as Fz}from"path";import FX from"process";import{existsSync as K2,mkdirSync as v3,readdirSync as c3,writeFileSync as i3}from"fs";import{homedir as HU}from"os";import{dirname as d3,resolve as m0}from"path";import MY from"process";import{join as Uq,relative as Wq,resolve as Nz}from"path";import NX from"process";import{existsSync as F2,mkdirSync as t3,readdirSync as a3,writeFileSync as s3}from"fs";import{dirname as e3,resolve as qX}from"path";import gU from"process";import{Buffer as Fw}from"buffer";import{createCipheriv as Bq,createDecipheriv as jq,randomBytes as RU}from"crypto";import{closeSync as MU,createReadStream as qz,createWriteStream as zq,existsSync as IU,fsyncSync as Ez,openSync as Tz,writeFileSync as Gq}from"fs";import{access as Kq,constants as fz,mkdir as Fq,readdir as lA,rename as Hz,stat as T1,unlink as nA,writeFile as VU}from"fs/promises";import{join as f1}from"path";import _0 from"process";import{pipeline as Nq}from"stream/promises";import{createGzip as Rz}from"zlib";import H1 from"process";import d$ from"process";import{Buffer as i$}from"buffer";import{createCipheriv as qq,createDecipheriv as Eq,randomBytes as CU}from"crypto";import{closeSync as QU,createReadStream as Mz,createWriteStream as Tq,existsSync as pA,fsyncSync as Iz,openSync as Vz,writeFileSync as fq}from"fs";import{access as Hq,constants as Cz,mkdir as Rq,readdir as rA,rename as Qz,stat as R1,unlink as tA,writeFile as yU}from"fs/promises";import{isAbsolute as Mq,join as M1,resolve as Iq}from"path";import l from"process";import{pipeline as Vq}from"stream/promises";import{createGzip as yz}from"zlib";import I1 from"process";import l$ from"process";import aA from"process";import{existsSync as sA}from"fs";import{resolve as OU}from"path";import{existsSync as Cq}from"fs";import{existsSync as Qq,readdirSync as yq}from"fs";import{extname as LU,resolve as Oz}from"path";import Oq from"process";import{join as Lq,relative as _q,resolve as Lz}from"path";import EX from"process";import{Buffer as m$}from"buffer";import{createCipheriv as Sq,createDecipheriv as Zq,randomBytes as _U}from"crypto";import{closeSync as SU,createReadStream as _z,createWriteStream as hq,existsSync as oA,fsyncSync as Sz,openSync as Zz,writeFileSync as Dq}from"fs";import{access as kq,constants as hz,mkdir as xq,readdir as eA,rename as Dz,stat as V1,unlink as $X,writeFile as ZU}from"fs/promises";import{isAbsolute as Pq,join as C1,resolve as bq}from"path";import n from"process";import{pipeline as uq}from"stream/promises";import{createGzip as kz}from"zlib";import Q1 from"process";import n$ from"process";import wX from"process";import{existsSync as YX}from"fs";import{resolve as hU}from"path";import{existsSync as vq}from"fs";import{exec as WT}from"node:child_process";import $W from"node:fs";import BT from"node:os";import F$ from"node:path";import t2 from"node:process";import{promisify as jT}from"node:util";import _1 from"node:crypto";import p$ from"node:fs";import AW from"node:path";import hT from"node:crypto";import{execSync as xT}from"node:child_process";import LX from"node:os";async function oz($,w,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=$.split(".").slice(-2).join("."),U;try{let j=new EU,z=await j.resolveNs(J),G=(await Promise.all(z.map((K)=>j.resolve4(K).catch(()=>[])))).flat();if(G.length>0)U=new EU,U.setServers(G)}catch{}let B=Date.now()+A,W=U??new EU;for(;;){try{if((await W.resolveTxt($)).some((j)=>j.join("")===w))return!0}catch{}if(Date.now()>=B)return!1;await new Promise((j)=>setTimeout(j,X))}}class RY{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(RY.PATH_PREFIX);if(w===-1)return;let Y=$.slice(w+RY.PATH_PREFIX.length);return this.get(Y)}}function JX($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function uU($){return Buffer.from($,"base64url")}function ez($){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 $2($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return vN("sha256").update(w).digest("base64url")}function w2($){let{protectedHeader:w,payload:Y,privateKey:A}=$,X=JX(JSON.stringify(w)),J=Y===""?"":JX(JSON.stringify(Y)),U=`${X}.${J}`,B=cN("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:JX(B)}}class KX{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=ez($.accountPublicKey),this.thumbprint=$2(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:Y,useJwk:A}=$,X={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=w2({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)}),B=U.headers.get("replay-nonce");if(B)this.nonce=B;let W=U.headers.get("content-type")??"",j;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))j=await U.text();else{let z=await U.text();j=z?JSON.parse(z):{}}if(U.status>=400){let z=j??{};throw new GX(`ACME request to ${w} failed (HTTP ${U.status}): ${z.type??""} ${z.detail??""}`.trim(),z,U.status)}return{status:U.status,headers:U.headers,body:j,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),Y={termsOfServiceAgreed:!0};if($.email)Y.contact=[`mailto:${$.email}`];let A=await this.signedPost({url:w.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder($){let w=await this.directory(),Y={identifiers:$.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:w.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return iN("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization($);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((B)=>B.status==="invalid");throw new GX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await Wz(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder($);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${$} became invalid`);await Wz(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 X2($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=w[0];if(!Y)return{certPem:`${$.trim()}
|
|
62
|
+
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
63
|
+
`;return Y}}function fF(w,$,Y={}){return tj(w,$,Y,new WeakMap)}function tj(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return aj(w,$,X,A);if(!Uw($)||!Uw(w))return $;return IF(w,$,Y,A)}function aj(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return HF(w,$);case"smart":return RF(w,$,A);default:return $}return $}function HF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>YU(X,A)))Y.push(A);return Y}function RF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Uw($[0])&&Uw(w[0]))return MF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function MF(w,$,Y){let A=[...$];for(let X of w){if(!Uw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((B)=>Uw(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function IF(w,$,Y,A){let X=$;if(Uw(X)&&A.has(X))return A.get(X);let J={...w};if(Uw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(Uw(W)&&Uw(Q))J[U]=tj(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=aj(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function sj(w,$,Y="replace"){return fF(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function YU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!YU(w[Y],$[Y]))return!1;return!0}if(Uw(w)&&Uw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!YU(w[X],$[X]))return!1}return!0}return!1}function Uw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class oj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=Y;if(X){let B=LA.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!RA(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new vA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new vA(w,Error("Configuration must export a valid object"),"unknown");let N={config:sj($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)LA.setWithFileCheck("file",N,w,J);return N}catch(B){throw B instanceof Error?G1.configLoad(w,B):G1.configLoad(w,Error(String(B)))}};if(U)return AU.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(gJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return TF(async()=>{return RA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!RA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=gJ(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=gJ(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!RA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class ej{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await AU.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!VF($))throw new iA($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new iA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:CF},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function yF(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class w9{fileLoader=new oj;envProcessor=new GU;validator=new ej;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)Lw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let Q=Date.now()-$;throw Lw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||mA.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(Xw(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw G1.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${yF(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?MA(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)Lw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)Lw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?MA(w,Y,X):Y,W=[Xw(w1(),".config",w),Xw(w1(),".config"),w1()];for(let Q of W){if(X)Lw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)Lw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?MA(w,A,J):A;try{let Q=Xw(Y,"package.json");if(!fK(Q))return null;let B={};try{B=JSON.parse(HK(Q,"utf8"))}catch(G){if(J)Lw.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[w],z=w;if(!j&&$){let G=Array.isArray($)?$:[$];for(let K of G){if(!K)continue;if(B[K]){j=B[K],z=K;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)Lw.success(`Configuration loaded from package.json: ${z}`);return{config:sj(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)Lw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:MA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw G1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return LA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);LA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Xw(w,"config"),Xw(w,".config"),$?Xw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Xw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Xw(w1(),".config",w),Xw(w1(),".config"),w1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function KU(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await dJ.loadConfig(w);else A=await dJ.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Lw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await dJ.applyEnvironmentVariables(W.name||"",$,!0,W.verbose||!1))?.config??$;return $}}function MA(w,$,Y=!1){let A=new GU,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=mA.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}var LA,AU,J7,U7=(w)=>w,W7=(w,$)=>{for(var Y in $)J7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:Q7.bind($,Y)})},B7=(w,$)=>()=>(w&&($=w(w=0)),$),Ij,kj,z1,EY,hj,P7,b7,Qj,VA,rJ,L0,a,u7,Wj,c7,Bj,v7,i7,uJ,m7,jj,zj,cJ,g7,d7,l7,n7,CA,Dj,p7,_0,r7,t7,Gj,yA,tJ,q0,u,a7,Kj,s7,Fj,o7,e7,vJ,wF,qj,Nj,$F,iJ,YF,AF,XF,JF,UF,OA,xj,QF,WF="0.15.6",o0,bA,qY,aJ,sJ,uA,oJ,eJ,NY,wU,$U,N$,Pj,bj,qw,dw,uj,cj,BF,zF,vj,cA,mI,I0,i,gI,KF,dI,FF,lI,nI,Ej,pI,qF,NF,rI,Tj,tI,aI,sI,oI,eI,mJ,EF,wV,Nw,mj,vA,gj,dj,zU,lj,nj,iA,pj,rj,G1,CF,Lw,dJ,JV,UV;var FU=t(()=>{LA=new fj,AU=new Hj,J7=Object.defineProperty;Ij={};W7(Ij,{withErrorRecovery:()=>yj,tryLoadConfig:()=>k7,loadConfigWithResult:()=>S7,loadConfig:()=>Zj,isRetryableError:()=>V7,isConfigNotFoundError:()=>I7,isBunfigError:()=>Oj,globalPerformanceMonitor:()=>EY,globalCache:()=>z1,getEnvOrDefault:()=>C7,generateConfigTypes:()=>h7,defaultGeneratedDir:()=>cj,defaultConfigDir:()=>uj,deepMergeWithArrayStrategy:()=>WU,deepMerge:()=>Lj,createLibraryConfig:()=>D7,config:()=>Z7,bunfigPlugin:()=>x7,applyEnvVarsToConfig:()=>KY,TypeGenerationError:()=>eJ,SchemaValidationError:()=>NY,PluginError:()=>$U,PerformanceMonitor:()=>JU,FileSystemError:()=>oJ,ErrorFactory:()=>N$,EnvVarError:()=>uA,EnvProcessor:()=>gA,ConfigValidator:()=>BU,ConfigValidationError:()=>aJ,ConfigNotFoundError:()=>bA,ConfigMergeError:()=>sJ,ConfigLoader:()=>jU,ConfigLoadError:()=>qY,ConfigFileLoader:()=>dA,ConfigCache:()=>XU,CacheUtils:()=>hj,BunfigError:()=>o0,BrowserConfigError:()=>wU,ArrayMergeStrategies:()=>Pj});BF=B7(async()=>{kj=import.meta.require,z1=new XU,EY=new JU,hj={createKey:j7,isEquivalent:z7,estimateMemoryUsage:G7},P7=ZA(nJ.cwd(),"config"),b7=ZA(nJ.cwd(),"src/generated"),Qj=SA.env.CLARITY_LOG_DIR||yK(q7(),"logs"),VA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Qj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},rJ=await N7(),L0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},a=L0,u7=L0.red,Wj=L0.green,c7=L0.yellow,Bj=L0.blue,v7=L0.magenta,i7=L0.cyan,uJ=L0.white,m7=L0.gray,jj=L0.bgRed,zj=L0.bgYellow,cJ=L0.bold,g7=L0.dim,d7=L0.italic,l7=L0.underline,n7=L0.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Dj={debug:"\uD83D\uDD0D",info:Bj("ℹ"),success:Wj("✓"),warning:zj(uJ(cJ(" WARN "))),error:jj(uJ(cJ(" ERROR ")))},p7=new DA("stacks"),_0=new DA("bunfig",{showTags:!0}),r7=v0(FY.cwd(),"config"),t7=v0(FY.cwd(),"src/generated"),Gj=_A.env.CLARITY_LOG_DIR||VK(H7(),"logs"),yA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Gj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},tJ=await R7(),q0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=q0,a7=q0.red,Kj=q0.green,s7=q0.yellow,Fj=q0.blue,o7=q0.magenta,e7=q0.cyan,vJ=q0.white,wF=q0.gray,qj=q0.bgRed,Nj=q0.bgYellow,$F=q0.bgGray,iJ=q0.bold,YF=q0.dim,AF=q0.italic,XF=q0.underline,JF=q0.strikethrough,UF=q0.reset,OA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xj={debug:"\uD83D\uDD0D",info:Fj("ℹ"),success:Kj("✓"),warning:Nj(vJ(iJ(" WARN "))),error:qj(vJ(iJ(" ERROR ")))},QF=new PA("stacks"),o0=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},bA=class extends o0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},qY=class extends o0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},aJ=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},sJ=class extends o0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},uA=class extends o0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},oJ=class extends o0{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},eJ=class extends o0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},NY=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},wU=class extends o0{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},$U=class extends o0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},N$={configNotFound(w,$,Y){return new bA(w,$,Y)},configLoad(w,$,Y){return new qY(w,$,Y)},configValidation(w,$,Y){return new aJ(w,$,Y)},configMerge(w,$,Y,A){return new sJ(w,$,Y,A)},envVar(w,$,Y,A){return new uA(w,$,Y,A)},fileSystem(w,$,Y){return new oJ(w,$,Y)},typeGeneration(w,$,Y){return new eJ(w,$,Y)},schemaValidation(w,$,Y){return new NY(w,$,Y)},browserConfig(w,$,Y,A){return new wU(w,$,Y,A)},plugin(w,$,Y){return new $U(w,$,Y)}},Pj={replace:"replace",concat:"concat",smart:"smart"},bj=/^https?:\/\//,qw=new PA("bunfig",{showTags:!0}),dw=new jU,uj=i0(b$.cwd(),"config"),cj=i0(b$.cwd(),"src/generated")});zF=kA.env.CLARITY_LOG_DIR||rK(jF(),"logs"),vj={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zF,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},cA={...vj},mI=(async()=>{try{let{loadConfig:w}=await BF().then(()=>Ij),$=await w({name:"clarity",alias:"logging",defaultConfig:vj,cwd:kA.cwd()});if($)Object.assign(cA,$)}catch{}return cA})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},i=I0,gI=I0.red,KF=I0.green,dI=I0.yellow,FF=I0.blue,lI=I0.magenta,nI=I0.cyan,Ej=I0.white,pI=I0.gray,qF=I0.bgRed,NF=I0.bgYellow,rI=I0.bgGray,Tj=I0.bold,tI=I0.dim,aI=I0.italic,sI=I0.underline,oI=I0.strikethrough,eI=I0.reset,mJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EF={debug:"\uD83D\uDD0D",info:FF("ℹ"),success:KF("✓"),warning:NF(Ej(Tj(" WARN "))),error:qF(Ej(Tj(" ERROR ")))};wV=new lA("stacks");Nw=class Nw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};mj=class mj extends Nw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};vA=class vA extends Nw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};gj=class gj extends Nw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};dj=class dj extends Nw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};zU=class zU extends Nw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};lj=class lj extends Nw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};nj=class nj extends Nw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};iA=class iA extends Nw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};pj=class pj extends Nw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};rj=class rj extends Nw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};G1={configNotFound(w,$,Y){return new mj(w,$,Y)},configLoad(w,$,Y){return new vA(w,$,Y)},configValidation(w,$,Y){return new gj(w,$,Y)},configMerge(w,$,Y,A){return new dj(w,$,Y,A)},envVar(w,$,Y,A){return new zU(w,$,Y,A)},fileSystem(w,$,Y){return new lj(w,$,Y)},typeGeneration(w,$,Y){return new nj(w,$,Y)},schemaValidation(w,$,Y){return new iA(w,$,Y)},browserConfig(w,$,Y,A){return new pj(w,$,Y,A)},plugin(w,$,Y){return new rj(w,$,Y)}};CF=/^https?:\/\//;Lw=new lA("bunfig",{showTags:!0});dJ=new w9;JV=Xw(mA.cwd(),"config"),UV=Xw(mA.cwd(),"src/generated")});function F1(w){return w.startsWith("*.")}function TY(w,$){if(!F1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function nA(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!F1(J))continue;if(TY($,J)){let W=J.length-1;if(W>X)X=W,A=U}}return A}var H;var lw=t(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as iF}from"node:module";import{Resolver as HU}from"node:dns/promises";import{createHash as gF,sign as dF}from"node:crypto";import{createHash as lF}from"node:crypto";import{sign as nF}from"node:crypto";import{generateKeyPairSync as Kz,X509Certificate as $q}from"node:crypto";import RU from"node:os";import MU from"node:path";import{existsSync as B9,statSync as j9}from"fs";import{existsSync as Aq,mkdirSync as _V,readdirSync as SV,readFileSync as Xq,writeFileSync as ZV}from"fs";import{homedir as N1}from"os";import{dirname as DV,resolve as Ww}from"path";import DX from"process";import{existsSync as z9,statSync as G9}from"fs";import{existsSync as nU,mkdirSync as Jq,readdirSync as Uq,writeFileSync as Qq}from"fs";import{homedir as E1}from"os";import{dirname as K9,resolve as g0}from"path";import v$ from"process";import{join as Wq,relative as Bq,resolve as F9}from"path";import EX from"process";import{existsSync as Fz,mkdirSync as dV,readdirSync as lV,writeFileSync as nV}from"fs";import{homedir as IU}from"os";import{dirname as tV,resolve as m0}from"path";import IY from"process";import{join as jq,relative as zq,resolve as q9}from"path";import TX from"process";import{existsSync as qz,mkdirSync as w3,readdirSync as $3,writeFileSync as Y3}from"fs";import{dirname as X3,resolve as fX}from"path";import pU from"process";import{Buffer as E$}from"buffer";import{createCipheriv as Gq,createDecipheriv as Kq,randomBytes as VU}from"crypto";import{closeSync as CU,createReadStream as N9,createWriteStream as Fq,existsSync as yU,fsyncSync as E9,openSync as T9,writeFileSync as qq}from"fs";import{access as Nq,constants as f9,mkdir as Eq,readdir as rA,rename as H9,stat as T1,unlink as tA,writeFile as OU}from"fs/promises";import{join as f1}from"path";import S0 from"process";import{pipeline as Tq}from"stream/promises";import{createGzip as R9}from"zlib";import H1 from"process";import tw from"process";import{Buffer as nw}from"buffer";import{createCipheriv as fq,createDecipheriv as Hq,randomBytes as LU}from"crypto";import{closeSync as _U,createReadStream as M9,createWriteStream as Rq,existsSync as aA,fsyncSync as I9,openSync as V9,writeFileSync as Mq}from"fs";import{access as Iq,constants as C9,mkdir as Vq,readdir as sA,rename as y9,stat as R1,unlink as oA,writeFile as SU}from"fs/promises";import{isAbsolute as Cq,join as M1,resolve as yq}from"path";import l from"process";import{pipeline as Oq}from"stream/promises";import{createGzip as O9}from"zlib";import I1 from"process";import aw from"process";import eA from"process";import{existsSync as wX}from"fs";import{resolve as ZU}from"path";import{existsSync as Lq}from"fs";import{existsSync as _q,readdirSync as Sq}from"fs";import{extname as kU,resolve as L9}from"path";import Zq from"process";import{join as kq,relative as hq,resolve as _9}from"path";import HX from"process";import{Buffer as pw}from"buffer";import{createCipheriv as Dq,createDecipheriv as xq,randomBytes as hU}from"crypto";import{closeSync as DU,createReadStream as S9,createWriteStream as Pq,existsSync as $X,fsyncSync as Z9,openSync as k9,writeFileSync as bq}from"fs";import{access as uq,constants as h9,mkdir as cq,readdir as YX,rename as D9,stat as V1,unlink as AX,writeFile as xU}from"fs/promises";import{isAbsolute as vq,join as C1,resolve as iq}from"path";import n from"process";import{pipeline as mq}from"stream/promises";import{createGzip as x9}from"zlib";import y1 from"process";import sw from"process";import XX from"process";import{existsSync as JX}from"fs";import{resolve as PU}from"path";import{existsSync as gq}from"fs";import{exec as zE}from"node:child_process";import XQ from"node:fs";import GE from"node:os";import Ew from"node:path";import sz from"node:process";import{promisify as KE}from"node:util";import S1 from"node:crypto";import ow from"node:fs";import QQ from"node:path";import PE from"node:crypto";import{execSync as cE}from"node:child_process";import kX from"node:os";async function WX(w,$={},Y=30000){try{return await fetch(w,{...$,signal:AbortSignal.timeout(Y)})}catch(A){if(A&&typeof A==="object"&&A.name==="TimeoutError"){let X=Error(`ACME HTTP request to ${w} timed out after ${Y}ms`);throw X.name="AcmeRequestTimeoutError",X}throw A}}async function wz(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let B=new HU,j=await B.resolveNs(J),z=(await Promise.all(j.map((G)=>B.resolve4(G).catch(()=>[])))).flat();if(z.length>0)U=new HU,U.setServers(z)}catch{}let W=Date.now()+A,Q=U??new HU;for(;;){try{if((await Q.resolveTxt(w)).some((B)=>B.join("")===$))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,X))}}class MY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(MY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+MY.PATH_PREFIX.length);return this.get(Y)}}function BX(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function mU(w){return Buffer.from(w,"base64url")}function $z(w){let $=w.export({format:"jwk"});if($.kty!=="EC"||$.crv!=="P-256"||!$.x||!$.y)throw Error(`Expected a P-256 EC public key, got kty=${$.kty} crv=${$.crv}`);return{crv:"P-256",kty:"EC",x:$.x,y:$.y}}function Yz(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return gF("sha256").update($).digest("base64url")}function Az(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=BX(JSON.stringify($)),J=Y===""?"":BX(JSON.stringify(Y)),U=`${X}.${J}`,W=dF("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:BX(W)}}class NX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=$z(w.accountPublicKey),this.thumbprint=Yz(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??e9}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let w=await WX(this.directoryUrl,{},this.requestTimeoutMs);if(!w.ok)throw Error(`Failed to fetch ACME directory: HTTP ${w.status}`);return this.directoryCache=await w.json(),this.directoryCache}async newNonce(){let w=await this.directory(),$=(await WX(w.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!$)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=$,$}async ensureNonce(){if(this.nonce){let w=this.nonce;return this.nonce=void 0,w}return this.newNonce()}async signedPost(w){let{url:$,payload:Y,useJwk:A}=w,X={alg:"ES256",nonce:await this.ensureNonce(),url:$};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=Az({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await WX($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let Q=U.headers.get("content-type")??"",B;if(Q.includes("application/pem-certificate-chain")||Q.startsWith("text/"))B=await U.text();else{let j=await U.text();B=j?JSON.parse(j):{}}if(U.status>=400){let j=B??{};throw new qX(`ACME request to ${$} failed (HTTP ${U.status}): ${j.type??""} ${j.detail??""}`.trim(),j,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return lF("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((W)=>W.status==="invalid");throw new qX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await W9(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${w} to become valid`)}async finalizeOrder(w,$){return(await this.signedPost({url:w,payload:{csr:$}})).body}async getOrder(w){return(await this.signedPost({url:w,payload:""})).body}async pollOrder(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder(w);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${w} became invalid`);await W9(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${w} to become valid`)}async downloadCertificate(w){let $=await this.signedPost({url:w,payload:""});return typeof $.body==="string"?$.body:String($.body)}static selectChallenge(w,$){let Y=w.challenges.find((A)=>A.type===$);if(!Y)throw Error(`No ${$} challenge available for ${w.identifier.value}`);return Y}}function Uz(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
|
|
64
64
|
`,chainPem:""};let A=`${Y.trim()}
|
|
65
|
-
`,X
|
|
65
|
+
`,X=$.slice(1).map((J)=>J.trim()).join(`
|
|
66
66
|
`);return{certPem:A,chainPem:X?`${X}
|
|
67
|
-
`:""}}function J2($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function Wz($){return new Promise((w)=>setTimeout(w,$))}function gN($){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 Ew($,w){return Buffer.concat([Buffer.from([$]),gN(w.length),w])}function U2($){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 Ew(2,w)}function Pw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let Y=[40*w[0]+w[1]];for(let A=2;A<w.length;A++){let X=w[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return Ew(6,Buffer.from(Y))}function J$(...$){return Ew(48,Buffer.concat($))}function vU(...$){return Ew(49,Buffer.concat($))}function cU($){return Ew(3,Buffer.concat([Buffer.from([0]),$]))}function W2($){return Ew(4,$)}function B2($){return Ew(12,Buffer.from($,"utf8"))}function iU($,w,Y){let A=128|(Y?32:0)|$;return Ew(A,w)}function aN($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let Y=uU(w.x),A=uU(w.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function j2($){let{domains:w,publicKey:Y,privateKey:A}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let X=J$(vU(J$(Pw(pN),B2(w[0])))),J=J$(J$(Pw(dN),Pw(lN)),cU(aN(Y))),U=w.map((q)=>iU(2,Buffer.from(q,"ascii"),!1)),B=J$(...U),W=J$(Pw(tN),W2(B)),j=J$(W),z=J$(Pw(rN),vU(j)),G=iU(0,z,!0),K=J$(U2(0),X,J,G),F=mN("sha256",K,A),T=J$(Pw(nN));return J$(K,T,cU(F))}function z2($){return j2($).toString("base64url")}function oN($){if($){let{createPrivateKey:X,createPublicKey:J}=uN("node:crypto"),U=X($),B=J(U);return{privateKey:U,publicKey:B,pem:$}}let{privateKey:w,publicKey:Y}=G2("ec",{namedCurve:"P-256"}),A=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:Y,pem:A}}async function XW($){let{domains:w,method:Y}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((G)=>G.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=$.directoryUrl??($.staging===!1?A2:Y2),X=oN($.accountKeyPem),J=new KX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey});await J.newAccount({email:$.email});let{order:U,orderUrl:B}=await J.newOrder(w),W=$.http01Store??_X,j=[],z=[];try{for(let f of U.authorizations){let I=await J.getAuthorization(f);if(I.status==="valid")continue;let L=KX.selectChallenge(I,Y);if(Y==="dns-01"){let Z=J2(I.identifier.value),P0=J.dns01TxtValue(L.token);await $.dnsProvider.setTxt(Z,P0),j.push({name:Z,value:P0}),await oz(Z,P0,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else W.add(L.token,J.keyAuthorization(L.token)),z.push(L.token);await J.notifyChallengeReady(L.url),await J.pollAuthorization(f,{timeoutMs:$.timeoutMs})}let{privateKey:G,publicKey:K}=G2("ec",{namedCurve:"P-256"}),F=z2({domains:w,publicKey:K,privateKey:G});await J.finalizeOrder(U.finalize,F);let T=await J.pollOrder(B,{timeoutMs:$.timeoutMs}),q=await J.downloadCertificate(T),{certPem:E,chainPem:H}=X2(q),M=H?`${E}${H}`:E,y=G.export({format:"pem",type:"pkcs8"}).toString(),C=new Date(new sN(E).validTo);return{certPem:E,keyPem:y,chainPem:H,fullChainPem:M,accountKeyPem:X.pem,notAfter:C}}finally{for(let{name:G,value:K}of j)await $.dnsProvider?.removeTxt(G,K).catch(()=>{});for(let G of z)W.remove(G)}}class N2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!Bz($))return!0;return jz($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Bz(Y)?jz(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class q2{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function mq($,w){this[$]=iq.bind(null,w)}class UW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!zz($))return!0;return Gz($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=zz(Y)?Gz(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class WW{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function lq($,w={}){let Y=Object.keys(w).sort().map((A)=>`${A}:${w[A]}`).join("|");return Y?`${$}:${Y}`:$}function nq($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function pq($){return $.getStats().size*2}function BW($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&w0(w[0])&&"id"in w[0]&&w[0].id===3&&w0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(w0(w)&&w0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(w0($)&&"arr"in $&&Array.isArray($.arr)&&w0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&w0(w[0])&&w0($[0])){let A=[...w];for(let X of $)if(w0(X)&&"name"in X){if(!A.find((J)=>w0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((J)=>w0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>fX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!w0(w)||!w0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=BW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&w0(X[0])&&w0(Y[A][0])){let J=[...X];for(let U of Y[A])if(w0(U)&&"name"in U){if(!J.find((B)=>w0(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((B)=>w0(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>fX(B,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function fX($,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(!fX($[Y],w[Y]))return!1;return!0}if(w0($)&&w0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!fX($[X],w[X]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function rq($,w){if(!F2($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return BW(w,A)}catch{return null}}catch{return null}}async function tq({name:$="",cwd:w,defaultConfig:Y}){let A=w||gU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=qX(A,`${U}${B}`),j=await rq(W,Y);if(j!==null)return j}try{let U=qX(A,"package.json");if(F2(U)){let B=(await import(U))[$];if(B&&typeof B==="object"&&!Array.isArray(B))try{return BW(Y,B)}catch{}}}catch{}return Y}function aq($,w={}){let Y=NX.cwd();while(Y.includes("storage"))Y=Nz(Y,"..");let A=Nz(Y,$||"");if(w?.relative)return Wq(NX.cwd(),A);return A}async function sq(){try{let $=await tq({name:"clarity",defaultConfig:WX,cwd:NX.cwd(),endpoint:"",headers:{}});return{...WX,...$}}catch{return WX}}function W0(){if(d$.env.NODE_ENV==="test"||d$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oq(){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 T2{async format($){let w=await oq(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:H1.pid,hostname:w(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class HX{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={...lU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new T2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...BX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...BX};return{...BX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:lU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Kq(this.config.logDirectory,fz.F_OK|fz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Fq(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Fw.from($);try{if(!IU(this.currentLogFile))await VU(this.currentLogFile,"",{mode:420});if(A=Tz(this.currentLogFile,"a",420),Gq(A,B,{flag:"a"}),Ez(A),A!==void 0)MU(A),A=void 0;if((await T1(this.currentLogFile)).size===0){if(await VU(this.currentLogFile,B,{flag:"w",mode:420}),(await T1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{MU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return f1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return f1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return f1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return RU(16).toString("hex")}generateKey(){return RU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=RU(16),A=Bq("aes-256-gcm",w,Y),X=Fw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Fw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Rz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Fw.from(Fw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W0())return;let $=await T1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await lA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await T1(Y).catch(()=>null))try{if(await Hz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await nA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await VU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await T1(Y).catch(()=>null))await Hz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await lA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await nA(f1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=qz($),A=zq(w),X=Rz();await Nq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),IU(this.currentLogFile))try{let $=Tz(this.currentLogFile,"r+");Ez($),MU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await lA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await nA(f1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?s.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=_0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${s.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!W0()){let j=O2[$],z=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
|
|
68
|
-
`);for(let
|
|
69
|
-
`;if(
|
|
70
|
-
`;
|
|
71
|
-
`,
|
|
72
|
-
`),U=Math.max(...J.map((
|
|
73
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(
|
|
74
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(
|
|
75
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||W0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await lA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=f1(this.config.logDirectory,A);if($.before)try{if((await T1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function UX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let A=[...w];for(let X of $)if(p(X)&&"name"in X){if(!A.find((J)=>p(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(p(X)&&"path"in X){if(!A.find((J)=>p(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>RX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!p(w)||!p($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=UX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&p(X[0])&&p(Y[A][0])){let J=[...X];for(let U of Y[A])if(p(U)&&"name"in U){if(!J.find((B)=>p(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((B)=>p(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>RX(B,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function jW($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:UX($,w);if(Array.isArray($))return Y==="replace"?w:UX($,w);if(!p(w)||!p($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=UX(U,J);else if(p(J)&&p(U))A[X]=jW(U,J,Y);else A[X]=J}return A}function RX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!RX($[Y],w[Y]))return!1;return!0}if(p($)&&p(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!RX($[X],w[X]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AX($,w,Y="replace"){if(!K2($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return jW(w,X,Y)}catch{return null}}catch{return null}}function eq($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=MY.env[F]||MY.env[T];if(q!==void 0){if(Y)Z0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((H)=>H.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function $E({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?eq($,X,J):X,j=Y||MY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,m0(j,"config"),m0(j,".config"),A?m0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)Z0.info(`Searching for configuration in: ${E}`);let H=[m0(j,"config"),m0(j,".config")].concat(A?[m0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let M of H)for(let y of z){let C=m0(E,`${M}${y}`),f=await AX(C,W,B);if(f!==null){if(J)Z0.success(`Configuration loaded from: ${C}`);return f}}}if($){let E=m0(HU(),".config",$),H=["config",`${$}.config`];if(w)H.push(`${w}.config`);if(J)Z0.info(`Checking user config directory: ${E}`);for(let M of H)for(let y of z){let C=m0(E,`${M}${y}`),f=await AX(C,W,B);if(f!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${C}`);return f}}}if($){let E=m0(HU(),".config"),H=[`.${$}.config`];if(w)H.push(`.${w}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of H)for(let y of z){let C=m0(E,`${M}${y}`),f=await AX(C,W,B);if(f!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${C}`);return f}}}if($){let E=HU(),H=[`.${$}.config`,`.${$}`];if(w)H.push(`.${w}.config`),H.push(`.${w}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of H)for(let y of z){let C=m0(E,`${M}${y}`),f=await AX(C,W,B);if(f!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${C}`);return f}}}try{let E=m0(j,"package.json");if(K2(E)){let H=await import(E),M=H[$];if(!M&&w){if(M=H[w],M&&J)Z0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)Z0.success(`Configuration loaded from package.json: ${M===H[$]?$:w}`);return jW(W,M,B)}catch(y){if(J)Z0.warn("Failed to merge package.json config:",y)}}}catch(E){if(J)Z0.warn("Failed to load package.json:",E)}if(J)Z0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function wE($,w={}){let Y=FX.cwd();while(Y.includes("storage"))Y=Fz(Y,"..");let A=Fz(Y,$||"");if(w?.relative)return Jq(FX.cwd(),A);return A}async function YE(){try{let $=await $E({name:"clarity",alias:"logging",defaultConfig:jX,cwd:FX.cwd()});return{...jX,...$||{}}}catch{return jX}}function E0(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function AE(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l$<"u"){let $=l$.type;if($==="renderer"||$==="worker")return!1;return!!(l$.versions&&(l$.versions.node||l$.versions.bun))}return!1}class f2{async format($){let w=await AE(),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 MX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...nU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new f2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...zX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...zX};return{...zX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Hq(this.config.logDirectory,Cz.F_OK|Cz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Rq(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:i$.from($);try{if(!pA(this.currentLogFile))await yU(this.currentLogFile,"",{mode:420});if(A=Vz(this.currentLogFile,"a",420),fq(A,B,{flag:"a"}),Iz(A),A!==void 0)QU(A),A=void 0;if((await R1(this.currentLogFile)).size===0){if(await yU(this.currentLogFile,B,{flag:"w",mode:420}),(await R1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{QU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return CU(16).toString("hex")}generateKey(){return CU(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=CU(16),A=qq("aes-256-gcm",w,Y),X=i$.isBuffer($)?$:i$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=i$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=yz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(i$.from(i$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let $=await 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 X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await R1(Y).catch(()=>null))try{if(await Qz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await tA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await yU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await R1(Y).catch(()=>null))await Qz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await rA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await tA(M1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Mz($),A=Tq(w),X=yz();await Vq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),pA(this.currentLogFile))try{let $=Vz(this.currentLogFile,"r+");Iz($),QU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await rA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await tA(M1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let $=typeof l.env.NO_COLOR<"u",w=l.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=l.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${v.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),w}supportsHyperlinks(){if(E0())return!1;let $=l.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=l.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Mq(w)||w.startsWith("./")||w.startsWith("../"))w=Iq(w);else return null;return pA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":L2[$],K=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:v.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:v.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
|
|
76
|
-
`);for(let q of
|
|
77
|
-
`;if(
|
|
78
|
-
`;if(
|
|
79
|
-
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(
|
|
80
|
-
`,
|
|
81
|
-
`),
|
|
82
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(
|
|
84
|
-
`)}finishProgressBar(
|
|
67
|
+
`:""}}function Qz(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function W9(w){return new Promise(($)=>setTimeout($,w))}function pF(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function H$(w,$){return Buffer.concat([Buffer.from([w]),pF($.length),$])}function Wz(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return H$(2,$)}function c$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return H$(6,Buffer.from(Y))}function Qw(...w){return H$(48,Buffer.concat(w))}function gU(...w){return H$(49,Buffer.concat(w))}function dU(w){return H$(3,Buffer.concat([Buffer.from([0]),w]))}function Bz(w){return H$(4,w)}function jz(w){return H$(12,Buffer.from(w,"utf8"))}function lU(w,$,Y){let A=128|(Y?32:0)|w;return H$(A,$)}function wq(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=mU($.x),A=mU($.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 zz(w){let{domains:$,publicKey:Y,privateKey:A}=w;if($.length===0)throw Error("At least one domain is required to build a CSR");let X=Qw(gU(Qw(c$(sF),jz($[0])))),J=Qw(Qw(c$(rF),c$(tF)),dU(wq(Y))),U=$.map((q)=>lU(2,Buffer.from(q,"ascii"),!1)),W=Qw(...U),Q=Qw(c$(eF),Bz(W)),B=Qw(Q),j=Qw(c$(oF),gU(B)),z=lU(0,j,!0),G=Qw(Wz(0),X,J,z),K=nF("sha256",G,A),E=Qw(c$(aF));return Qw(G,E,dU(K))}function Gz(w){return zz(w).toString("base64url")}function Yq(w){if(w){let{createPrivateKey:X,createPublicKey:J}=mF("node:crypto"),U=X(w),W=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:W,pem:w}}let{privateKey:$,publicKey:Y}=Kz("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function WQ(w){let{domains:$,method:Y}=w;if($.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!w.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if($.some((z)=>z.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?Jz:Xz),X=Yq(w.accountKeyPem),J=new NX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:W}=await J.newOrder($),Q=w.http01Store??hX,B=[],j=[];try{for(let T of U.authorizations){let M=await J.getAuthorization(T);if(M.status==="valid")continue;let O=NX.selectChallenge(M,Y);if(Y==="dns-01"){let S=Qz(M.identifier.value),B0=J.dns01TxtValue(O.token);await w.dnsProvider.setTxt(S,B0),B.push({name:S,value:B0}),await wz(S,B0,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else Q.add(O.token,J.keyAuthorization(O.token)),j.push(O.token);await J.notifyChallengeReady(O.url),await J.pollAuthorization(T,{timeoutMs:w.timeoutMs})}let{privateKey:z,publicKey:G}=Kz("ec",{namedCurve:"P-256"}),K=Gz({domains:$,publicKey:G,privateKey:z});await J.finalizeOrder(U.finalize,K);let E=await J.pollOrder(W,{timeoutMs:w.timeoutMs}),q=await J.downloadCertificate(E),{certPem:N,chainPem:f}=Uz(q),R=f?`${N}${f}`:N,y=z.export({format:"pem",type:"pkcs8"}).toString(),V=new Date(new $q(N).validTo);return{certPem:N,keyPem:y,chainPem:f,fullChainPem:R,accountKeyPem:X.pem,notAfter:V}}finally{for(let{name:z,value:G}of B)await w.dnsProvider?.removeTxt(z,G).catch(()=>{});for(let z of j)Q.remove(z)}}class Nz{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!B9(w))return!0;return j9(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=B9(Y)?j9(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Ez{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function nq(w,$){this[w]=lq.bind(null,$)}class jQ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!z9(w))return!0;return G9(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=z9(Y)?G9(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class zQ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function tq(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function aq(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function sq(w){return w.getStats().size*2}function GQ(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&$0($[0])&&"id"in $[0]&&$[0].id===3&&$0($[1])&&"id"in $[1]&&$[1].id===4)return $;if($0($)&&$0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if($0(w)&&"arr"in w&&Array.isArray(w.arr)&&$0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&$0($[0])&&$0(w[0])){let A=[...$];for(let X of w)if($0(X)&&"name"in X){if(!A.find((J)=>$0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if($0(X)&&"path"in X){if(!A.find((J)=>$0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>MX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!$0($)||!$0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=GQ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&$0(X[0])&&$0(Y[A][0])){let J=[...X];for(let U of Y[A])if($0(U)&&"name"in U){if(!J.find((W)=>$0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if($0(U)&&"path"in U){if(!J.find((W)=>$0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((W)=>MX(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function MX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!MX(w[Y],$[Y]))return!1;return!0}if($0(w)&&$0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!MX(w[X],$[X]))return!1}return!0}return!1}function $0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function oq(w,$){if(!qz(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return GQ($,A)}catch{return null}}catch{return null}}async function eq({name:w="",cwd:$,defaultConfig:Y}){let A=$||pU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=fX(A,`${U}${W}`),B=await oq(Q,Y);if(B!==null)return B}try{let U=fX(A,"package.json");if(qz(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return GQ(Y,W)}catch{}}}catch{}return Y}function wN(w,$={}){let Y=TX.cwd();while(Y.includes("storage"))Y=q9(Y,"..");let A=q9(Y,w||"");if($?.relative)return zq(TX.cwd(),A);return A}async function $N(){try{let w=await eq({name:"clarity",defaultConfig:zX,cwd:TX.cwd(),endpoint:"",headers:{}});return{...zX,...w}}catch{return zX}}function Q0(){if(tw.env.NODE_ENV==="test"||tw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YN(){if(tw.env.NODE_ENV==="test"||tw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tw<"u"){let w=tw.type;if(w==="renderer"||w==="worker")return!1;return!!(tw.versions&&(tw.versions.node||tw.versions.bun))}return!1}class fz{async format(w){let $=await YN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:H1.pid,hostname:$(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class IX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...tU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new fz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??S0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...GX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...GX};return{...GX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:tU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Nq(this.config.logDirectory,f9.F_OK|f9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Eq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:E$.from(w);try{if(!yU(this.currentLogFile))await OU(this.currentLogFile,"",{mode:420});if(A=T9(this.currentLogFile,"a",420),qq(A,W,{flag:"a"}),E9(A),A!==void 0)CU(A),A=void 0;if((await T1(this.currentLogFile)).size===0){if(await OU(this.currentLogFile,W,{flag:"w",mode:420}),(await T1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let B=Q;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((G)=>setTimeout(G,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{CU(A)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let Q=U*2**(X-1);await new Promise((B)=>setTimeout(B,Q))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return f1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return f1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return f1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(Q0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return VU(16).toString("hex")}generateKey(){return VU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=VU(16),A=Gq("aes-256-gcm",$,Y),X=E$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:E$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=R9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(E$.from(E$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(Q0())return;let w=await T1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await T1(Y).catch(()=>null))try{if(await H9(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await tA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await OU(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await T1(Y).catch(()=>null))await H9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await rA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await tA(f1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=N9(w),A=Fq($),X=R9();await Tq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),yU(this.currentLogFile))try{let w=T9(this.currentLogFile,"r+");E9(w),CU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!Q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await rA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await tA(f1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?s.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=S0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${s.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!Q0()){let B=_z[w],j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:s.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:s.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
|
|
68
|
+
`);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:s.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!Q0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
|
|
69
|
+
`;if(W)Q+=`${W}
|
|
70
|
+
`;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=performance.now();if(this.fancy&&!Q0()){let Y=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:s.blue("◐"),tag:Y,message:`${s.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
|
|
71
|
+
`,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!Q0()){let B=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:s.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!Q0())console.error(Q.trim());await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new IX($,{...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(!yU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return N9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=E$.isBuffer(w)?w:E$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=Kq("aes-256-gcm",Y,X);return W.setAuthTag(J),E$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q0()}isServerMode(){return!Q0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!Q0()){let J=w.split(`
|
|
72
|
+
`),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:s.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(Q),showTimestamp:!1}))}else if(!Q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
|
|
73
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(Q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${s.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();S0.stdin.removeListener("data",Y);try{if(typeof S0.stdin.setRawMode==="function")S0.stdin.setRawMode(!1)}catch{}S0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof S0.stdin.setRawMode==="function")S0.stdin.setRawMode(!0)}catch{}S0.stdin.resume(),S0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,W)=>{if(W==="%")return"%";if(J>=$.length)return U;let Q=$[J++];switch(W){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!Q0()){let X=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",J=s.blue("◐");console.error(`${J} ${X} ${s.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
74
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||Q0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;S0.stdout.write(`${"\r".padEnd(S0.stdout.columns||80)}\r`),this.log(X,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||Q0()||!S0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=s.green("━".repeat(A)),U=s.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?s.green("✓"):s.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=S0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,S0.stdout.write(w.lastRenderedLine),$)S0.stdout.write(`
|
|
75
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||Q0()||!S0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(Q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await rA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=f1(this.config.logDirectory,A);if(w.before)try{if((await T1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await tA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function jX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&p($[0])&&"id"in $[0]&&$[0].id===3&&p($[1])&&"id"in $[1]&&$[1].id===4)return $;if(p($)&&p(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(p(w)&&"arr"in w&&Array.isArray(w.arr)&&p($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&p($[0])&&p(w[0])){let A=[...$];for(let X of w)if(p(X)&&"name"in X){if(!A.find((J)=>p(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(p(X)&&"path"in X){if(!A.find((J)=>p(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>VX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!p($)||!p(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=jX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&p(X[0])&&p(Y[A][0])){let J=[...X];for(let U of Y[A])if(p(U)&&"name"in U){if(!J.find((W)=>p(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((W)=>p(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((W)=>VX(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function KQ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:jX(w,$);if(Array.isArray(w))return Y==="replace"?$:jX(w,$);if(!p($)||!p(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=jX(U,J);else if(p(J)&&p(U))A[X]=KQ(U,J,Y);else A[X]=J}return A}function VX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!VX(w[Y],$[Y]))return!1;return!0}if(p(w)&&p($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!VX(w[X],$[X]))return!1}return!0}return!1}function p(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function UX(w,$,Y="replace"){if(!Fz(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return KQ($,X,Y)}catch{return null}}catch{return null}}function AN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)k0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=IY.env[K]||IY.env[E];if(q!==void 0){if(Y)k0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function XN({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?AN(w,X,J):X,B=Y||IY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)k0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,m0(B,"config"),m0(B,".config"),A?m0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)k0.info(`Searching for configuration in: ${N}`);let f=[m0(B,"config"),m0(B,".config")].concat(A?[m0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let R of f)for(let y of j){let V=m0(N,`${R}${y}`),T=await UX(V,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from: ${V}`);return T}}}if(w){let N=m0(IU(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)k0.info(`Checking user config directory: ${N}`);for(let R of f)for(let y of j){let V=m0(N,`${R}${y}`),T=await UX(V,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from user config directory: ${V}`);return T}}}if(w){let N=m0(IU(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)k0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let y of j){let V=m0(N,`${R}${y}`),T=await UX(V,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from user config directory dotfile: ${V}`);return T}}}if(w){let N=IU(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)k0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let y of j){let V=m0(N,`${R}${y}`),T=await UX(V,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from user home directory: ${V}`);return T}}}try{let N=m0(B,"package.json");if(Fz(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)k0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)k0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return KQ(Q,R,W)}catch(y){if(J)k0.warn("Failed to merge package.json config:",y)}}}catch(N){if(J)k0.warn("Failed to load package.json:",N)}if(J)k0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function JN(w,$={}){let Y=EX.cwd();while(Y.includes("storage"))Y=F9(Y,"..");let A=F9(Y,w||"");if($?.relative)return Bq(EX.cwd(),A);return A}async function UN(){try{let w=await XN({name:"clarity",alias:"logging",defaultConfig:KX,cwd:EX.cwd()});return{...KX,...w||{}}}catch{return KX}}function E0(){if(aw.env.NODE_ENV==="test"||aw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function QN(){if(aw.env.NODE_ENV==="test"||aw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof aw<"u"){let w=aw.type;if(w==="renderer"||w==="worker")return!1;return!!(aw.versions&&(aw.versions.node||aw.versions.bun))}return!1}class Hz{async format(w){let $=await QN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:I1.pid,hostname:$(),environment:I1.env.NODE_ENV||"development",platform:I1.platform,version:I1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I1.env.NODE_ENV||I1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class CX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...aU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Hz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...FX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...FX};return{...FX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:aU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Iq(this.config.logDirectory,C9.F_OK|C9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Vq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:nw.from(w);try{if(!aA(this.currentLogFile))await SU(this.currentLogFile,"",{mode:420});if(A=V9(this.currentLogFile,"a",420),Mq(A,W,{flag:"a"}),I9(A),A!==void 0)_U(A),A=void 0;if((await R1(this.currentLogFile)).size===0){if(await SU(this.currentLogFile,W,{flag:"w",mode:420}),(await R1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let B=Q;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((G)=>setTimeout(G,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{_U(A)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let Q=U*2**(X-1);await new Promise((B)=>setTimeout(B,Q))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 w=new Date().toISOString().split("T")[0];return M1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return LU(16).toString("hex")}generateKey(){return LU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=LU(16),A=fq("aes-256-gcm",$,Y),X=nw.isBuffer(w)?w:nw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=nw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=O9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(nw.from(nw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await R1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await sA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await R1(Y).catch(()=>null))try{if(await y9(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await oA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await SU(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await R1(Y).catch(()=>null))await y9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await sA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await oA(M1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=M9(w),A=Rq($),X=O9();await Oq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),aA(this.currentLogFile))try{let w=V9(this.currentLogFile,"r+");I9(w),_U(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await sA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await oA(M1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof l.env.NO_COLOR<"u",$=l.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=l.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${c.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=l.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=l.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(Cq($)||$.startsWith("./")||$.startsWith("../"))$=yq($);else return null;return aA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Sz[w],G=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:c.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:c.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
|
|
76
|
+
`);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
|
|
77
|
+
`;if(W)j+=`${W}
|
|
78
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!E0()&&l.stdout.isTTY)l.stdout.write(`
|
|
79
|
+
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
|
|
80
|
+
`,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":c.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new CX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(E0())throw Error("createReadStream is not supported in browser environments");if(!aA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return M9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=nw.isBuffer(w)?w:nw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=Hq("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=nw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E0()}isServerMode(){return!E0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
|
|
81
|
+
`),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
82
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(E0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${c.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();l.stdin.removeListener("data",Y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${W}${U} ${c.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!l.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=l.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,l.stdout.write(w.lastRenderedLine),$)l.stdout.write(`
|
|
84
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||E0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await sA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=M1(this.config.logDirectory,A);if(w.before)try{if((await R1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await oA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Rz(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Mz(w){return w instanceof e0}function WN(w){return w instanceof yX}function BN(w){if(Mz(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>w.message.toLowerCase().includes($.toLowerCase()))}class xX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return OY.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=eA.env[Q]||(B?eA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=eA.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof OX)throw z;throw f$.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw f$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(eA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
85
85
|
|
|
86
|
-
`;for(let A of
|
|
86
|
+
`;for(let A of w)Y+=`${A.key}
|
|
87
87
|
`,Y+=` Type: ${A.type}
|
|
88
88
|
`,Y+=` Description: ${A.description}
|
|
89
89
|
`,Y+=` Example: ${A.example}
|
|
90
90
|
|
|
91
|
-
`;return Y}formatAsMarkdown(
|
|
91
|
+
`;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
|
|
92
92
|
|
|
93
93
|
`;Y+=`| Variable | Type | Description | Example |
|
|
94
94
|
`,Y+=`|----------|------|-------------|----------|
|
|
95
|
-
`;for(let A of
|
|
96
|
-
`;return Y}}function UE($,w){let Y=Q2("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function M2($,w,Y={}){return I2($,w,Y,new WeakMap)}function I2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return V2($,w,X,A);if(!W$(w)||!W$($))return w;return zE($,w,Y,A)}function V2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return WE($,w);case"smart":return BE($,w,A);default:return w}return w}function WE($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>dU(X,A)))Y.push(A);return Y}function BE($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return jE($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function jE($,w,Y){let A=[...w];for(let X of $){if(!W$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>W$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function zE($,w,Y,A){let X=w;if(W$(X)&&A.has(X))return A.get(X);let J={...$};if(W$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(W$(B)&&W$(W))J[U]=I2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=V2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function zW($,w,Y="replace"){return M2($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function dU($,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(!dU($[Y],w[Y]))return!1;return!0}if(W$($)&&W$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!dU($[X],w[X]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class hX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=O1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!sA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new IY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new IY($,Error("Configuration must export a valid object"),"unknown");let T={config:zW(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)O1.setWithFileCheck("file",T,$,J);return T}catch(j){throw j instanceof Error?qw.configLoad($,j):qw.configLoad($,Error(String(j)))}};if(U)return QY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(OU(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return H2(async()=>{return sA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!sA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=OU($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=OU($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!sA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class GW{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await QY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!Cq(w))throw new VY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new VY(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],X=[];return this.validateObjectAgainstSchema($,w,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema($,w,Y,A,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:S2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class KW{fileLoader=new hX;envProcessor=new ZX;validator=new GW;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)N$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw N$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||bw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(g0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw qw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?fY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)N$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)N$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?fY($,Y,X):Y,B=[g0(E1(),".config",$),g0(E1(),".config"),E1()];for(let W of B){if(X)N$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)N$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?fY($,A,J):A;try{let W=g0(Y,"package.json");if(!mU(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)N$.success(`Configuration loaded from package.json: ${G}`);return{config:zW(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)N$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:fY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw qw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return O1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);O1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,g0($,"config"),g0($,".config"),w?g0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths($,w,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[g0(E1(),".config",$),g0(E1(),".config"),E1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function xz($){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 GE($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function C2($){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 X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)N$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function KE($={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"&&xz(Y)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await r$.loadConfig({...$,cwd:$.cwd||bw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&xz(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function FE($,w,Y="replace"){let A=new hX;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function fY($,w,Y=!1){let A=new ZX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=bw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function NE($){let w=g0(bw.cwd(),$.configDir),Y=g0(bw.cwd(),$.generatedDir),A=g0(Y,"config-types.ts");if(!mU(Kz(A)))wq(Kz(A),{recursive:!0,mode:511});let X=mU(w)?Yq(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${gE}
|
|
95
|
+
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
96
|
+
`;return Y}}function jN(w,$){let Y=Oz("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function Iz(w,$,Y={}){return Vz(w,$,Y,new WeakMap)}function Vz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return Cz(w,$,X,A);if(!Bw($)||!Bw(w))return $;return FN(w,$,Y,A)}function Cz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return zN(w,$);case"smart":return GN(w,$,A);default:return $}return $}function zN(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>rU(X,A)))Y.push(A);return Y}function GN(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Bw($[0])&&Bw(w[0]))return KN(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function KN(w,$,Y){let A=[...$];for(let X of w){if(!Bw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((Q)=>Bw(Q)&&(W in Q)&&Q[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function FN(w,$,Y,A){let X=$;if(Bw(X)&&A.has(X))return A.get(X);let J={...w};if(Bw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(Bw(W)&&Bw(Q))J[U]=Vz(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=Cz(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function FQ(w,$,Y="replace"){return Iz(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function rU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!rU(w[Y],$[Y]))return!1;return!0}if(Bw(w)&&Bw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!rU(w[X],$[X]))return!1}return!0}return!1}function Bw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class PX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=Y;if(X){let B=L1.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!wX(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new VY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new VY(w,Error("Configuration must export a valid object"),"unknown");let E={config:FQ($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)L1.setWithFileCheck("file",E,w,J);return E}catch(B){throw B instanceof Error?f$.configLoad(w,B):f$.configLoad(w,Error(String(B)))}};if(U)return OY.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(ZU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Rz(async()=>{return wX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!wX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=ZU(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=ZU(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!wX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class qQ{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await OY.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!Lq($))throw new CY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new CY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:kz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class NQ{fileLoader=new PX;envProcessor=new xX;validator=new qQ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)Tw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){let Q=Date.now()-$;throw Tw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||v$.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(g0(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw f$.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?HY(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)Tw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)Tw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?HY(w,Y,X):Y,W=[g0(E1(),".config",w),g0(E1(),".config"),E1()];for(let Q of W){if(X)Tw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)Tw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?HY(w,A,J):A;try{let Q=g0(Y,"package.json");if(!nU(Q))return null;let B=await import(Q),j=B[w],z=w;if(!j&&$)j=B[$],z=$;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)Tw.success(`Configuration loaded from package.json: ${z}`);return{config:FQ(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)Tw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:HY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw f$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return L1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);L1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(E1(),".config",w),g0(E1(),".config"),E1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function P9(w){let $=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),Y=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return $||Y}async function qN(w){return ew.loadConfig({...w,__strictErrorHandling:!0})}async function yz(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await ew.loadConfig(w);else A=await ew.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Tw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await ew.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function NN(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await ew.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&P9(Y)))return(await ew.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await ew.loadConfig({...w,cwd:w.cwd||v$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&P9($)))return(await ew.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function EN(w,$,Y="replace"){let A=new PX;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function HY(w,$,Y=!1){let A=new xX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=v$.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function TN(w){let $=g0(v$.cwd(),w.configDir),Y=g0(v$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!nU(K9(A)))Jq(K9(A),{recursive:!0,mode:511});let X=nU($)?Uq($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${pN}
|
|
97
97
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
98
|
-
`;
|
|
99
|
-
${X.map((
|
|
98
|
+
`;Qq(A,J,{mode:438})}function fN(w){let $=null,Y=null,A=()=>{if(!Y)Y=yz(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Tw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let W=X[U];return A(),W},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,W){if(!$)$={...X};return $[U]=W,!0}})}function HN(w){let $=L9(Zq.cwd(),w?.configDir||"./config");function Y(){if(!_q($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=Sq($).filter((Q)=>X.has(kU(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),W=new Map;for(let{base:Q,file:B}of U){let j=kU(B).toLowerCase(),z=W.get(Q);if(!z){W.set(Q,B);continue}let G=kU(z).toLowerCase();if(J.indexOf(j)<J.indexOf(G))W.set(Q,B)}return Array.from(W.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",W=X.length?`{
|
|
99
|
+
${X.map((Q)=>{let B=L9($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${B}').default`}).join(`,
|
|
100
100
|
`)}
|
|
101
101
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
102
|
-
export type ConfigByName = ${
|
|
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:A(),loader:"ts"}})}}}function lE($,w={}){let Y=EX.cwd();while(Y.includes("storage"))Y=Lz(Y,"..");let A=Lz(Y,$||"");if(w?.relative)return _q(EX.cwd(),A);return A}function f0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pE(){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 k2{async format($){let w=await pE(),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 DX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...CX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new k2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...bU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...bU};return{...bU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:CX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!f0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await kq(this.config.logDirectory,hz.F_OK|hz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await xq(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:m$.from($);try{if(!oA(this.currentLogFile))await ZU(this.currentLogFile,"",{mode:420});if(A=Zz(this.currentLogFile,"a",420),Dq(A,B,{flag:"a"}),Sz(A),A!==void 0)SU(A),A=void 0;if((await V1(this.currentLogFile)).size===0){if(await ZU(this.currentLogFile,B,{flag:"w",mode:420}),(await V1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{SU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return C1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return C1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return C1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return _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(),Y=_U(16),A=Sq("aes-256-gcm",w,Y),X=m$.isBuffer($)?$:m$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=m$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=kz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(m$.from(m$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f0())return;if(!this.shouldWriteToFile())return;let $=await V1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await eA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await V1(Y).catch(()=>null))try{if(await Dz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await $X(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await ZU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await V1(Y).catch(()=>null))await Dz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await eA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await $X(C1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=_z($),A=hq(w),X=kz();await uq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),oA(this.currentLogFile))try{let $=Zz(this.currentLogFile,"r+");Sz($),SU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await eA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await $X(C1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f0())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=n.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${m.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),w}supportsHyperlinks(){if(f0())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=n.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Pq(w)||w.startsWith("./")||w.startsWith("../"))w=bq(w);else return null;return oA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":oE[$],K=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:m.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:m.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
|
|
106
|
-
`);for(let q of
|
|
107
|
-
`;if(
|
|
108
|
-
`;if(
|
|
109
|
-
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!f0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(
|
|
110
|
-
`,
|
|
111
|
-
`),
|
|
112
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(
|
|
113
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(
|
|
114
|
-
`)}finishProgressBar(
|
|
105
|
+
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function tN(w,$={}){let Y=HX.cwd();while(Y.includes("storage"))Y=_9(Y,"..");let A=_9(Y,w||"");if($?.relative)return hq(HX.cwd(),A);return A}function f0(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sN(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof sw<"u"){let w=sw.type;if(w==="renderer"||w==="worker")return!1;return!!(sw.versions&&(sw.versions.node||sw.versions.bun))}return!1}class Pz{async format(w){let $=await sN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:y1.pid,hostname:$(),environment:y1.env.NODE_ENV||"development",platform:y1.platform,version:y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:y1.env.NODE_ENV||y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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=w,this.config={...LX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Pz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...iU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...iU};return{...iU,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:LX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!f0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await uq(this.config.logDirectory,h9.F_OK|h9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await cq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:pw.from(w);try{if(!$X(this.currentLogFile))await xU(this.currentLogFile,"",{mode:420});if(A=k9(this.currentLogFile,"a",420),bq(A,W,{flag:"a"}),Z9(A),A!==void 0)DU(A),A=void 0;if((await V1(this.currentLogFile)).size===0){if(await xU(this.currentLogFile,W,{flag:"w",mode:420}),(await V1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let B=Q;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((G)=>setTimeout(G,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{DU(A)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let Q=U*2**(X-1);await new Promise((B)=>setTimeout(B,Q))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return C1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return C1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return C1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(f0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return hU(16).toString("hex")}generateKey(){return hU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=hU(16),A=Dq("aes-256-gcm",$,Y),X=pw.isBuffer(w)?w:pw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=pw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=x9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(pw.from(pw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(f0())return;if(!this.shouldWriteToFile())return;let w=await V1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await YX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await V1(Y).catch(()=>null))try{if(await D9(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await AX(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await xU(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await V1(Y).catch(()=>null))await D9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await YX(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await AX(C1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=S9(w),A=Pq($),X=x9();await mq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),$X(this.currentLogFile))try{let w=k9(this.currentLogFile,"r+");Z9(w),DU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await YX(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await AX(C1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f0())return!1;let w=typeof n.env.NO_COLOR<"u",$=n.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=n.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${m.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(f0())return!1;let w=n.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=n.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(vq($)||$.startsWith("./")||$.startsWith("../"))$=iq($);else return null;return $X($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":YE[w],G=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:m.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:m.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
|
|
106
|
+
`);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!f0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
|
|
107
|
+
`;if(W)j+=`${W}
|
|
108
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!f0()&&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()&&!f0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!f0()&&n.stdout.isTTY)n.stdout.write(`
|
|
109
|
+
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!f0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
|
|
110
|
+
`,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":m.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!f0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new bX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(f0())throw Error("createReadStream is not supported in browser environments");if(!$X(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return S9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=pw.isBuffer(w)?w:pw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=xq("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=pw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return f0()}isServerMode(){return!f0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
|
|
111
|
+
`),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(j),showTimestamp:!1}))}else if(!f0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
112
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(f0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();n.stdin.removeListener("data",Y);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${W}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
113
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=n.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,n.stdout.write(w.lastRenderedLine),$)n.stdout.write(`
|
|
114
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||f0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await YX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=C1(this.config.logDirectory,A);if(w.before)try{if((await V1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await AX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function AE(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class TQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return BQ.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=XX.env[Q]||(B?XX.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=XX.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof EQ)throw z;throw _1.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw _1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(XX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
115
115
|
|
|
116
|
-
`;for(let A of
|
|
116
|
+
`;for(let A of w)Y+=`${A.key}
|
|
117
117
|
`,Y+=` Type: ${A.type}
|
|
118
118
|
`,Y+=` Description: ${A.description}
|
|
119
119
|
`,Y+=` Example: ${A.example}
|
|
120
120
|
|
|
121
|
-
`;return Y}formatAsMarkdown(
|
|
121
|
+
`;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
|
|
122
122
|
|
|
123
123
|
`;Y+=`| Variable | Type | Description | Example |
|
|
124
124
|
`,Y+=`|----------|------|-------------|----------|
|
|
125
|
-
`;for(let A of
|
|
126
|
-
`;return Y}}function $T($,w,Y={}){return m2($,w,Y,new WeakMap)}function m2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return g2($,w,X,A);if(!B$(w)||!B$($))return w;return XT($,w,Y,A)}function g2($,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 wT($,w);case"smart":return YT($,w,A);default:return w}return w}function wT($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>eU(X,A)))Y.push(A);return Y}function YT($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(B$(w[0])&&B$($[0]))return AT($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function AT($,w,Y){let A=[...w];for(let X of $){if(!B$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>B$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function XT($,w,Y,A){let X=w;if(B$(X)&&A.has(X))return A.get(X);let J={...$};if(B$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(B$(B)&&B$(W))J[U]=m2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=g2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function d2($,w,Y="replace"){return $T($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function eU($,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(!eU($[Y],w[Y]))return!1;return!0}if(B$($)&&B$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!eU($[X],w[X]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class l2{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=TX.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!YX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new QX($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new QX($,Error("Configuration must export a valid object"),"unknown");let T={config:d2(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)TX.setWithFileCheck("file",T,$,J);return T}catch(j){throw j instanceof Error?L1.configLoad($,j):L1.configLoad($,Error(String(j)))}};if(U)return JW.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(hU(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return eE(async()=>{return YX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!YX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=hU($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=hU($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!YX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class n2{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await JW.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!vq(w))throw new yX(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new yX(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],X=[];return this.validateObjectAgainstSchema($,w,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema($,w,Y,A,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:JT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function UT($){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 p2{fileLoader=new l2;envProcessor=new NW;validator=new n2;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)g$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw g$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||SX.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(U$(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw L1.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${UT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?XX($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)g$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)g$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?XX($,Y,X):Y,B=[U$(q1(),".config",$),U$(q1(),".config"),q1()];for(let W of B){if(X)g$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)g$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?XX($,A,J):A;try{let W=U$(Y,"package.json");if(!eN(W))return null;let j={};try{j=JSON.parse($q(W,"utf8"))}catch(K){if(J)g$.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let z=j[$],G=$;if(!z&&w){let K=Array.isArray(w)?w:[w];for(let F of K){if(!F)continue;if(j[F]){z=j[F],G=F;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)g$.success(`Configuration loaded from package.json: ${G}`);return{config:d2(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)g$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:XX($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw L1.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return TX.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);TX.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,U$($,"config"),U$($,".config"),w?U$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(U$(Y,"package.json")),X}getLocalSearchPaths($,w,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[U$(q1(),".config",$),U$(q1(),".config"),q1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function XX($,w,Y=!1){let A=new NW,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=SX.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function a2($){return $W.readFileSync($,"utf8")}function wW($,w){let Y=[];function A(X){let J;try{J=$W.readdirSync(X)}catch{return}for(let U of J){let B=F$.join(X,U);try{if($W.statSync(B).isDirectory())A(B);else if(U===w)Y.push(X)}catch{continue}}}return A($),Y}function O($,w,Y){if(Y||z0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function s2(){return t2.env.SUDO_PASSWORD}function FT($){let w=$.toLowerCase();return GT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function OX($){if(Array.isArray($))return $.map((Y)=>OX(Y));if(typeof $==="string")return KT.test($)?rz:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(FT(Y)){w[Y]=rz;continue}w[Y]=OX(A)}return w}function kX($){return JSON.stringify(OX($))}function NT($){let w=s2();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 Nw($,w={}){let Y=NT($);try{let{stdout:A,stderr:X}=await zT(Y,{cwd:w.cwd||t2.cwd(),timeout:w.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${$}
|
|
127
|
-
Error: ${A.message}`);throw X.stack=A.stack,X}}function
|
|
125
|
+
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
126
|
+
`;return Y}}function XE(w,$,Y={}){return dz(w,$,Y,new WeakMap)}function dz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return lz(w,$,X,A);if(!jw($)||!jw(w))return $;return WE(w,$,Y,A)}function lz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return JE(w,$);case"smart":return UE(w,$,A);default:return $}return $}function JE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>AQ(X,A)))Y.push(A);return Y}function UE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return QE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function QE(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((Q)=>jw(Q)&&(W in Q)&&Q[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function WE(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(jw(W)&&jw(Q))J[U]=dz(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=lz(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function nz(w,$,Y="replace"){return XE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function AQ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!AQ(w[Y],$[Y]))return!1;return!0}if(jw(w)&&jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!AQ(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class pz{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=Y;if(X){let B=RX.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!JX(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new _X(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new _X(w,Error("Configuration must export a valid object"),"unknown");let E={config:nz($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)RX.setWithFileCheck("file",E,w,J);return E}catch(B){throw B instanceof Error?_1.configLoad(w,B):_1.configLoad(w,Error(String(B)))}};if(U)return BQ.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(PU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return AE(async()=>{return JX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!JX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=PU(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=PU(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!JX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class rz{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await BQ.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!gq($))throw new SX($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new SX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:BE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function jE(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class tz{fileLoader=new pz;envProcessor=new TQ;validator=new rz;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)rw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let Q=Date.now()-$;throw rw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||DX.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(Ww(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw _1.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${jE(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?QX(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)rw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)rw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?QX(w,Y,X):Y,W=[Ww(N1(),".config",w),Ww(N1(),".config"),N1()];for(let Q of W){if(X)rw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)rw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?QX(w,A,J):A;try{let Q=Ww(Y,"package.json");if(!Aq(Q))return null;let B={};try{B=JSON.parse(Xq(Q,"utf8"))}catch(G){if(J)rw.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[w],z=w;if(!j&&$){let G=Array.isArray($)?$:[$];for(let K of G){if(!K)continue;if(B[K]){j=B[K],z=K;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)rw.success(`Configuration loaded from package.json: ${z}`);return{config:nz(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)rw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:QX(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw _1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return RX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);RX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Ww(w,"config"),Ww(w,".config"),$?Ww(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Ww(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Ww(N1(),".config",w),Ww(N1(),".config"),N1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function QX(w,$,Y=!1){let A=new TQ,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=DX.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function oz(w){return XQ.readFileSync(w,"utf8")}function JQ(w,$){let Y=[];function A(X){let J;try{J=XQ.readdirSync(X)}catch{return}for(let U of J){let W=Ew.join(X,U);try{if(XQ.statSync(W).isDirectory())A(W);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function L(w,$,Y){if(Y||z0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function ez(){return sz.env.SUDO_PASSWORD}function EE(w){let $=w.toLowerCase();return qE.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function ZX(w){if(Array.isArray(w))return w.map((Y)=>ZX(Y));if(typeof w==="string")return NE.test(w)?t9:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(EE(Y)){$[Y]=t9;continue}$[Y]=ZX(A)}return $}function uX(w){return JSON.stringify(ZX(w))}function TE(w){let $=ez();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function T$(w,$={}){let Y=TE(w);try{let{stdout:A,stderr:X}=await FE(Y,{cwd:$.cwd||sz.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
|
|
127
|
+
Error: ${A.message}`);throw X.stack=A.stack,X}}function w2(w){if(w.domain)return w.domain;if(w.domains?.length)return w.domains[0];throw Error("Either domain or domains must be specified")}function fQ(w){let $=Ew.join(GE.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:z0.basePath&&z0.basePath.trim()!==""?z0.basePath:$,A=w.certPath?Ew.isAbsolute(w.certPath)?w.certPath:Ew.join(Y,w.certPath):Ew.join(Y,z0.certPath),X=w.keyPath?Ew.isAbsolute(w.keyPath)?w.keyPath:Ew.join(Y,w.keyPath):Ew.join(Y,z0.keyPath),J=w.caCertPath?Ew.isAbsolute(w.caCertPath)?w.caCertPath:Ew.join(Y,w.caCertPath):Ew.join(Y,z0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function $2(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return L(_.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function HQ(w){let $=w.notBeforeDays??fw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:fw.DEFAULT_VALIDITY_DAYS);L(_.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),L(_.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function RY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function $w(w,$){let Y=RY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function yY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return $w(Hw.OID,Buffer.from(Y))}function UQ(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return $w(Hw.INTEGER,$)}function Y2(w,$=0){return $w(Hw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function A2(w){return $w(Hw.OCTET_STRING,w)}function ww(...w){return $w(Hw.SEQUENCE,Buffer.concat(w))}function fE(...w){return $w(Hw.SET,Buffer.concat(w))}function HE(w){return $w(Hw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function RE(w){return $w(Hw.UTF8_STRING,Buffer.from(w,"utf8"))}function ME(){return Buffer.from([Hw.NULL,0])}function a9(w,$,Y=!0){let A=160|w|(Y?0:0),X=RY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function s9(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return $w(Hw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),W=w.getUTCSeconds().toString().padStart(2,"0"),Q=`${Y}${A}${X}${J}${U}${W}Z`;return $w(Hw.UTC_TIME,Buffer.from(Q,"ascii"))}}function IE(w,$){return ww(s9(w),s9($))}function o9(w){let $=[];for(let Y of w){let A;switch(Y.shortName){case"CN":A=d0.COMMON_NAME;break;case"C":A=d0.COUNTRY;break;case"L":A=d0.LOCALITY;break;case"ST":A=d0.STATE;break;case"O":A=d0.ORGANIZATION;break;case"OU":A=d0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?HE(Y.value):RE(Y.value),J=ww(yY(A),X);$.push(fE(J))}return ww(...$)}function X2(w){return ww(yY(w),ME())}function VE(w){return w.export({type:"spki",format:"der"})}function CE(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],W=8-J.length-U.length,Q=Array.from({length:W},()=>"0");$=[...J,...Q,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function yE(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=RY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=CE(Y.ip),X=RY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=RY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return ww(...$)}function OE(w,$){if(w){if($!==void 0)return ww($w(1,Buffer.from([255])),UQ($));return ww($w(1,Buffer.from([255])))}return ww()}function LE(w){let $=0;if(w.digitalSignature)$|=128;if(w.keyEncipherment)$|=32;if(w.keyCertSign)$|=4;if(w.cRLSign)$|=2;let Y=0,A=$;while(A>0&&(A&1)===0)Y++,A>>=1;if($===0)Y=7;return Y2(Buffer.from([$]),Y)}function _E(w){let $=[];if(w.serverAuth)$.push(yY(d0.SERVER_AUTH));if(w.clientAuth)$.push(yY(d0.CLIENT_AUTH));return ww(...$)}function fY(w,$,Y){let A=[yY(w)];if($)A.push($w(1,Buffer.from([255])));return A.push(A2(Y)),ww(...A)}function SE(w){let $=[];if($.push(a9(0,UQ(2))),$.push(UQ(w.serialNumber)),$.push(X2(d0.SHA256_WITH_RSA)),$.push(o9(w.issuer)),$.push(IE(w.notBefore,w.notAfter)),$.push(o9(w.subject)),$.push(VE(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push(fY(d0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,OE(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push(fY(d0.KEY_USAGE,w.extensions.keyUsage.critical??!0,LE(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push(fY(d0.EXTENDED_KEY_USAGE,!1,_E(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push(fY(d0.SUBJECT_ALT_NAME,!1,yE(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push(fY(d0.SUBJECT_KEY_IDENTIFIER,!1,A2(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(a9(3,ww(...Y)))}return ww(...$)}function ZE(w,$){let Y=S1.createSign("SHA256");Y.update(w);let A=Y.sign($);return ww(w,X2(d0.SHA256_WITH_RSA),Y2(A))}function kE(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
|
|
128
128
|
${A.join(`
|
|
129
129
|
`)}
|
|
130
|
-
-----END ${
|
|
131
|
-
`}function
|
|
132
|
-
`);for(let J of X){let[U,...
|
|
133
|
-
`);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)
|
|
134
|
-
`).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return O(_.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return O(_.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(Y){return O(_.TRUST,`Error checking certificate trust: ${Y}`,w),!1}}async function IW($,w,Y){O(_.TRUST,`Adding certificate to system trust store with options: ${kX(Y)}`,Y?.verbose),O(_.TRUST,"Storing certificate and private key",Y?.verbose);let A=U5($,Y);O(_.TRUST,"Storing CA certificate",Y?.verbose);let X=W5(w,Y),J=LX.platform();O(_.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=cT[J];if(!U){let B=`Unsupported platform: ${J}`;throw O(_.TRUST,`Error: ${B}`,Y?.verbose),Error(B)}return await U.addCertificate(X,Y),O(_.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var uN,_X,Y2="https://acme-staging-v02.api.letsencrypt.org/directory",A2="https://acme-v02.api.letsencrypt.org/directory",GX,dN="1.2.840.10045.2.1",lN="1.2.840.10045.3.1.7",nN="1.2.840.10045.4.3.2",pN="2.5.4.3",rN="1.2.840.113549.1.9.14",tN="2.5.29.17",TX,JW,cq,iq=($)=>$,gq=($,w)=>{for(var Y in w)cq($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:mq.bind(w,Y)})},dq=($,w)=>()=>($&&(w=$($=0)),w),E2,Q2,O1,QY,y2,TE,fE,Pz,WX,lU,S0,s,HE,bz,RE,uz,ME,IE,DU,VE,vz,cz,kU,CE,QE,yE,OE,BX,O2,LE,Z0,_E,SE,iz,jX,nU,T0,v,ZE,mz,hE,gz,DE,kE,xU,xE,dz,lz,PE,PU,bE,uE,vE,cE,iE,zX,L2,mE,gE="0.15.6",s0,IX,IY,pU,rU,VX,tU,aU,VY,sU,oU,qw,_2,S2,N$,r$,Z2,h2,dE,nE,D2,CX,dC,V0,m,lC,rE,nC,tE,pC,rC,nz,tC,aE,sE,aC,pz,sC,oC,eC,$Q,wQ,bU,oE,YQ,T$,x2,QX,P2,b2,FW,u2,v2,yX,c2,i2,L1,JT,g$,AQ,XQ,JQ,r2,z0,q$,_,y1,zT,rz="[redacted]",GT,KT,E$,d0,bT,uT,vT,cT;var j5=t(()=>{uN=bN(import.meta.url);_X=new RY;GX=class GX extends Error{problem;httpStatus;constructor($,w,Y){super($);this.name="AcmeError",this.problem=w,this.httpStatus=Y}};TX=new N2,JW=new q2,cq=Object.defineProperty;E2={};gq(E2,{withErrorRecovery:()=>H2,tryLoadConfig:()=>FE,loadConfigWithResult:()=>GE,loadConfig:()=>C2,isRetryableError:()=>JE,isConfigNotFoundError:()=>XE,isBunfigError:()=>R2,globalPerformanceMonitor:()=>QY,globalCache:()=>O1,getEnvOrDefault:()=>UE,generateConfigTypes:()=>NE,defaultGeneratedDir:()=>h2,defaultConfigDir:()=>Z2,deepMergeWithArrayStrategy:()=>zW,deepMerge:()=>M2,createLibraryConfig:()=>qE,config:()=>KE,bunfigPlugin:()=>EE,applyEnvVarsToConfig:()=>fY,TypeGenerationError:()=>aU,SchemaValidationError:()=>VY,PluginError:()=>oU,PerformanceMonitor:()=>WW,FileSystemError:()=>tU,ErrorFactory:()=>qw,EnvVarError:()=>VX,EnvProcessor:()=>ZX,ConfigValidator:()=>GW,ConfigValidationError:()=>pU,ConfigNotFoundError:()=>IX,ConfigMergeError:()=>rU,ConfigLoader:()=>KW,ConfigLoadError:()=>IY,ConfigFileLoader:()=>hX,ConfigCache:()=>UW,CacheUtils:()=>y2,BunfigError:()=>s0,BrowserConfigError:()=>sU,ArrayMergeStrategies:()=>_2});dE=dq(async()=>{Q2=import.meta.require,O1=new UW,QY=new WW,y2={createKey:lq,isEquivalent:nq,estimateMemoryUsage:pq},TE=qX(gU.cwd(),"config"),fE=qX(gU.cwd(),"src/generated"),Pz=NX.env.CLARITY_LOG_DIR||Uq(aq(),"logs"),WX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Pz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},lU=await sq(),S0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},s=S0,HE=S0.red,bz=S0.green,RE=S0.yellow,uz=S0.blue,ME=S0.magenta,IE=S0.cyan,DU=S0.white,VE=S0.gray,vz=S0.bgRed,cz=S0.bgYellow,kU=S0.bold,CE=S0.dim,QE=S0.italic,yE=S0.underline,OE=S0.reset,BX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},O2={debug:"\uD83D\uDD0D",info:uz("ℹ"),success:bz("✓"),warning:cz(DU(kU(" WARN "))),error:vz(DU(kU(" ERROR ")))},LE=new HX("stacks"),Z0=new HX("bunfig",{showTags:!0}),_E=m0(MY.cwd(),"config"),SE=m0(MY.cwd(),"src/generated"),iz=FX.env.CLARITY_LOG_DIR||Xq(wE(),"logs"),jX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:iz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},nU=await YE(),T0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},v=T0,ZE=T0.red,mz=T0.green,hE=T0.yellow,gz=T0.blue,DE=T0.magenta,kE=T0.cyan,xU=T0.white,xE=T0.gray,dz=T0.bgRed,lz=T0.bgYellow,PE=T0.bgGray,PU=T0.bold,bE=T0.dim,uE=T0.italic,vE=T0.underline,cE=T0.strikethrough,iE=T0.reset,zX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},L2={debug:"\uD83D\uDD0D",info:gz("ℹ"),success:mz("✓"),warning:lz(xU(PU(" WARN "))),error:dz(xU(PU(" ERROR ")))},mE=new MX("stacks"),s0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},IX=class extends s0{code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${A} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}},IY=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}},pU=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},rU=class extends s0{code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},VX=class extends s0{code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}},tU=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}},aU=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}},VY=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})}},sU=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})}},oU=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}},qw={configNotFound($,w,Y){return new IX($,w,Y)},configLoad($,w,Y){return new IY($,w,Y)},configValidation($,w,Y){return new pU($,w,Y)},configMerge($,w,Y,A){return new rU($,w,Y,A)},envVar($,w,Y,A){return new VX($,w,Y,A)},fileSystem($,w,Y){return new tU($,w,Y)},typeGeneration($,w,Y){return new aU($,w,Y)},schemaValidation($,w,Y){return new VY($,w,Y)},browserConfig($,w,Y,A){return new sU($,w,Y,A)},plugin($,w,Y){return new oU($,w,Y)}},_2={replace:"replace",concat:"concat",smart:"smart"},S2=/^https?:\/\//,N$=new MX("bunfig",{showTags:!0}),r$=new KW,Z2=g0(bw.cwd(),"config"),h2=g0(bw.cwd(),"src/generated")});nE=EX.env.CLARITY_LOG_DIR||Lq(lE(),"logs"),D2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:nE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},CX={...D2},dC=(async()=>{try{let{loadConfig:$}=await dE().then(()=>E2),w=await $({name:"clarity",alias:"logging",defaultConfig:D2,cwd:EX.cwd()});if(w)Object.assign(CX,w)}catch{}return CX})();V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},m=V0,lC=V0.red,rE=V0.green,nC=V0.yellow,tE=V0.blue,pC=V0.magenta,rC=V0.cyan,nz=V0.white,tC=V0.gray,aE=V0.bgRed,sE=V0.bgYellow,aC=V0.bgGray,pz=V0.bold,sC=V0.dim,oC=V0.italic,eC=V0.underline,$Q=V0.strikethrough,wQ=V0.reset,bU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oE={debug:"\uD83D\uDD0D",info:tE("ℹ"),success:rE("✓"),warning:sE(nz(pz(" WARN "))),error:aE(nz(pz(" ERROR ")))};YQ=new DX("stacks");T$=class T$ 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}${$}`}};x2=class x2 extends T${code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};QX=class QX extends T${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}};P2=class P2 extends T${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};b2=class b2 extends T${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}};FW=class FW extends T${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})}};u2=class u2 extends T${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}};v2=class v2 extends T${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};yX=class yX extends T${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};c2=class c2 extends T${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};i2=class i2 extends T${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}};L1={configNotFound($,w,Y){return new x2($,w,Y)},configLoad($,w,Y){return new QX($,w,Y)},configValidation($,w,Y){return new P2($,w,Y)},configMerge($,w,Y,A){return new b2($,w,Y,A)},envVar($,w,Y,A){return new FW($,w,Y,A)},fileSystem($,w,Y){return new u2($,w,Y)},typeGeneration($,w,Y){return new v2($,w,Y)},schemaValidation($,w,Y){return new yX($,w,Y)},browserConfig($,w,Y,A){return new c2($,w,Y,A)},plugin($,w,Y){return new i2($,w,Y)}};JT=/^https?:\/\//;g$=new DX("bunfig",{showTags:!0});AQ=new p2;XQ=U$(SX.cwd(),"config"),JQ=U$(SX.cwd(),"src/generated"),r2={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:fU.join(TU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:fU.join(TU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:fU.join(TU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=r2,q$={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"},_={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},y1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};zT=jT(WT);GT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),KT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;E$={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},d0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};bT={platform:"darwin",async addCertificate($,w){if(await PT($,w?.verbose)){O(_.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),y1.success("Certificate is already trusted in system keychain");return}O(_.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Nw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;O(_.TRUST,`Removing certificate ${A} from macOS keychain`,w?.verbose);try{await Nw(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),O(_.TRUST,`Removed certificate ${A} from macOS keychain`,w?.verbose)}catch(X){throw O(_.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},uT={platform:"win32",async addCertificate($,w){O(_.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Nw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;O(_.TRUST,`Removing certificate ${A} from Windows certificate store`,w?.verbose);try{await Nw(`certutil -delstore -enterprise Root "${A}"`),O(_.TRUST,`Removed certificate ${A} from Windows certificate store`,w?.verbose)}catch(X){throw O(_.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},vT={platform:"linux",async addCertificate($,w){O(_.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let Y=LX.homedir(),A=q$.LINUX_CERT_DB_FILENAME,X=q$.LINUX_TRUST_ARGS;O(_.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let J=wW(Y,A);if(J.length===0){y1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){O(_.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{O(_.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,w?.verbose),await Nw(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(B){O(_.TRUST,`Warning: Error deleting existing cert: ${B}`,w?.verbose),console.warn(`Error deleting existing cert: ${B}`)}O(_.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Nw(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${$}`),y1.info(`Cert added to ${U}`)}},async removeCertificate($,w,Y){let A=Y||z0.commonName;O(_.TRUST,`Removing certificate ${A} from Linux certificate store`,w?.verbose);let X=LX.homedir(),J=q$.LINUX_CERT_DB_FILENAME;O(_.TRUST,`Searching for certificate databases in ${X}`,w?.verbose);let U=wW(X,J);if(U.length===0){y1.warn("No certificate databases found. Cannot remove certificate.");return}for(let B of U){O(_.TRUST,`Processing certificate database in ${B}`,w?.verbose);try{await Nw(`certutil -d sql:${B} -D -n "${A}"`),y1.info(`Cert removed from ${B}`)}catch(W){O(_.TRUST,`Error removing cert from ${B}: ${W}`,w?.verbose),console.warn(`Error removing cert from ${B}: ${W}`)}}}},cT={darwin:bT,win32:uT,linux:vT}});var bX=t(()=>{j5()});import{homedir as VW}from"node:os";import{join as CW,resolve as $y}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",mT,QW;var yW=t(()=>{zU();mT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:CW(VW(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:CW(VW(),".stacks","ssl","stacks.localhost.crt"),keyPath:CW(VW(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},QW=mT});function uw($){try{return PX($)}catch{return null}}function OW($){try{return RW($)||null}catch{return null}}function uX($,w){try{return w.every((Y)=>MW($,Y))}catch{return!1}}var vX=t(()=>{bX()});import{existsSync as z5,statSync as G5}from"fs";import{existsSync as nW,mkdirSync as rT,readdirSync as tT,writeFileSync as aT}from"fs";import{homedir as S1}from"os";import{dirname as K5,resolve as n0}from"path";import vw from"process";import{join as sT,relative as oT,resolve as F5}from"path";import Y8 from"process";import{existsSync as t5,mkdirSync as Fy,readdirSync as Ny,writeFileSync as qy}from"fs";import{homedir as LW}from"os";import{dirname as fy,resolve as l0}from"path";import OY from"process";import{join as eT,relative as $f,resolve as N5}from"path";import A8 from"process";import{existsSync as a5,mkdirSync as Vy,readdirSync as Cy,writeFileSync as Qy}from"fs";import{dirname as Oy,resolve as X8}from"path";import pW from"process";import{Buffer as Tw}from"buffer";import{createCipheriv as wf,createDecipheriv as Yf,randomBytes as _W}from"crypto";import{closeSync as SW,createReadStream as q5,createWriteStream as Af,existsSync as ZW,fsyncSync as E5,openSync as T5,writeFileSync as Xf}from"fs";import{access as Jf,constants as f5,mkdir as Uf,readdir as cX,rename as H5,stat as Z1,unlink as iX,writeFile as hW}from"fs/promises";import{join as h1}from"path";import h0 from"process";import{pipeline as Wf}from"stream/promises";import{createGzip as R5}from"zlib";import D1 from"process";import s$ from"process";import{Buffer as t$}from"buffer";import{createCipheriv as Bf,createDecipheriv as jf,randomBytes as DW}from"crypto";import{closeSync as kW,createReadStream as M5,createWriteStream as zf,existsSync as mX,fsyncSync as I5,openSync as V5,writeFileSync as Gf}from"fs";import{access as Kf,constants as C5,mkdir as Ff,readdir as gX,rename as Q5,stat as k1,unlink as dX,writeFile as xW}from"fs/promises";import{isAbsolute as Nf,join as x1,resolve as qf}from"path";import x from"process";import{pipeline as Ef}from"stream/promises";import{createGzip as y5}from"zlib";import P1 from"process";import o$ from"process";import lX from"process";import{existsSync as nX}from"fs";import{resolve as PW}from"path";import{existsSync as Tf}from"fs";import{existsSync as ff,readdirSync as Hf}from"fs";import{extname as bW,resolve as O5}from"path";import Rf from"process";import{join as IH,relative as VH,resolve as v5}from"path";import G8 from"process";import{Buffer as a$}from"buffer";import{createCipheriv as yH,createDecipheriv as OH,randomBytes as mW}from"crypto";import{closeSync as gW,createReadStream as c5,createWriteStream as LH,existsSync as rX,fsyncSync as i5,openSync as m5,writeFileSync as _H}from"fs";import{access as SH,constants as g5,mkdir as ZH,readdir as tX,rename as d5,stat as b1,unlink as aX,writeFile as dW}from"fs/promises";import{isAbsolute as hH,join as u1,resolve as DH}from"path";import P from"process";import{pipeline as kH}from"stream/promises";import{createGzip as l5}from"zlib";import v1 from"process";import e$ from"process";function lT($,w){this[$]=dT.bind(null,w)}class A9{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!z5($))return!0;return G5($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=z5(Y)?G5(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class X9{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function Mf($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function If($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function Vf($){return $.getStats().size*2}function J9($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&Y0(w[0])&&"id"in w[0]&&w[0].id===3&&Y0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(Y0(w)&&Y0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(Y0($)&&"arr"in $&&Array.isArray($.arr)&&Y0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&Y0(w[0])&&Y0($[0])){let A=[...w];for(let X of $)if(Y0(X)&&"name"in X){if(!A.find((U)=>Y0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((U)=>Y0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>J8(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!Y0(w)||!Y0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=J9(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((W)=>Y0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((W)=>Y0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>J8(B,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function J8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!J8($[Y],w[Y]))return!1;return!0}if(Y0($)&&Y0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!J8($[X],w[X]))return!1}return!0}return!1}function Y0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Cf($,w){if(!a5($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return J9(w,A)}catch{return null}}catch{return null}}async function Qf({name:$="",cwd:w,defaultConfig:Y}){let A=w||pW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=X8(A,`${U}${B}`),j=await Cf(W,Y);if(j!==null)return j}try{let U=X8(A,"package.json");if(a5(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return J9(Y,W)}catch{}}}catch{}return Y}function yf($,w={}){let Y=A8.cwd();while(Y.includes("storage"))Y=N5(Y,"..");let A=N5(Y,$||"");if(w?.relative)return $f(A8.cwd(),A);return A}async function Of(){try{let $=await Qf({name:"clarity",defaultConfig:oX,cwd:A8.cwd(),endpoint:"",headers:{}});return{...oX,...$}}catch{return oX}}function B0(){if(s$.env.NODE_ENV==="test"||s$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lf(){if(s$.env.NODE_ENV==="test"||s$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof s$<"u"){let $=s$.type;if($==="renderer"||$==="worker")return!1;return!!(s$.versions&&(s$.versions.node||s$.versions.bun))}return!1}class s5{async format($){let w=await Lf(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:D1.pid,hostname:w(),environment:D1.env.NODE_ENV||"development",platform:D1.platform,version:D1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D1.env.NODE_ENV||D1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class U8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...tW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new s5,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??h0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...eX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...eX};return{...eX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:tW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await Jf(this.config.logDirectory,f5.F_OK|f5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await Uf(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Tw.from($);try{if(!ZW(this.currentLogFile))await hW(this.currentLogFile,"",{mode:420});if(X=T5(this.currentLogFile,"a",420),Xf(X,W,{flag:"a"}),E5(X),X!==void 0)SW(X),X=void 0;if((await Z1(this.currentLogFile)).size===0){if(await hW(this.currentLogFile,W,{flag:"w",mode:420}),(await Z1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{SW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return h1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return h1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return h1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(B0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return _W(16).toString("hex")}generateKey(){return _W(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=_W(16),A=wf("aes-256-gcm",w,Y),X=Tw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Tw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=R5(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Tw.from(Tw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(B0())return;let $=await Z1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await Z1(Y).catch(()=>null))try{if(await H5(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await iX(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await hW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await Z1(Y).catch(()=>null))await H5(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await cX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await iX(h1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=q5($),A=Af(w),X=R5();await Wf(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),ZW(this.currentLogFile))try{let $=T5(this.currentLogFile,"r+");E5($),SW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!B0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await cX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await iX(h1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?o.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=h0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${o.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!B0()){let j=WG[$],z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:o.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:o.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
|
|
135
|
-
`);for(let
|
|
136
|
-
`;if(
|
|
137
|
-
`;
|
|
138
|
-
`,
|
|
139
|
-
`),U=Math.max(...J.map((
|
|
140
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(
|
|
141
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(
|
|
142
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(B0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await cX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=h1(this.config.logDirectory,A);if($.before)try{if((await Z1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await iX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function sX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let A=[...w];for(let X of $)if(r(X)&&"name"in X){if(!A.find((U)=>r(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((U)=>r(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>W8(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!r(w)||!r($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=sX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&r(X[0])&&r(Y[A][0])){let J=[...X];for(let U of Y[A])if(r(U)&&"name"in U){if(!J.find((W)=>r(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((W)=>r(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((B)=>W8(B,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function U9($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:sX($,w);if(Array.isArray($))return Y==="replace"?w:sX($,w);if(!r(w)||!r($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=sX(U,J);else if(r(J)&&r(U))A[X]=U9(U,J,Y);else A[X]=J}return A}function W8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!W8($[Y],w[Y]))return!1;return!0}if(r($)&&r(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!W8($[X],w[X]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function pX($,w,Y="replace"){if(!t5($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return U9(w,X,Y)}catch{return null}}catch{return null}}function _f($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)k0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=OY.env[F]||OY.env[T];if(q!==void 0){if(Y)k0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((H)=>H.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function Sf({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?_f($,X,J):X,j=Y||OY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)k0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,l0(j,"config"),l0(j,".config"),A?l0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)k0.info(`Searching for configuration in: ${E}`);let M=[l0(j,"config"),l0(j,".config")].concat(A?[l0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let y of M)for(let C of z){let f=l0(E,`${y}${C}`),I=await pX(f,W,B);if(I!==null){if(J)k0.success(`Configuration loaded from: ${f}`);return I}}}if($){let E=l0(LW(),".config",$),H=["config",`${$}.config`];if(w)H.push(`${w}.config`);if(J)k0.info(`Checking user config directory: ${E}`);for(let M of H)for(let y of z){let C=l0(E,`${M}${y}`),f=await pX(C,W,B);if(f!==null){if(J)k0.success(`Configuration loaded from user config directory: ${C}`);return f}}}if($){let E=l0(LW(),".config"),H=[`.${$}.config`];if(w)H.push(`.${w}.config`);if(J)k0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of H)for(let y of z){let C=l0(E,`${M}${y}`),f=await pX(C,W,B);if(f!==null){if(J)k0.success(`Configuration loaded from user config directory dotfile: ${C}`);return f}}}if($){let E=LW(),H=[`.${$}.config`,`.${$}`];if(w)H.push(`.${w}.config`),H.push(`.${w}`);if(J)k0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of H)for(let y of z){let C=l0(E,`${M}${y}`),f=await pX(C,W,B);if(f!==null){if(J)k0.success(`Configuration loaded from user home directory: ${C}`);return f}}}try{let E=l0(j,"package.json");if(t5(E)){let H=await import(E),M=H[$];if(!M&&w){if(M=H[w],M&&J)k0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)k0.success(`Configuration loaded from package.json: ${M===H[$]?$:w}`);return U9(W,M,B)}catch(y){if(J)k0.warn("Failed to merge package.json config:",y)}}}catch(E){if(J)k0.warn("Failed to load package.json:",E)}if(J)k0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function Zf($,w={}){let Y=Y8.cwd();while(Y.includes("storage"))Y=F5(Y,"..");let A=F5(Y,$||"");if(w?.relative)return oT(Y8.cwd(),A);return A}async function hf(){try{let $=await Sf({name:"clarity",alias:"logging",defaultConfig:$8,cwd:Y8.cwd()});return{...$8,...$||{}}}catch{return $8}}function H0(){if(o$.env.NODE_ENV==="test"||o$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Df(){if(o$.env.NODE_ENV==="test"||o$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o$<"u"){let $=o$.type;if($==="renderer"||$==="worker")return!1;return!!(o$.versions&&(o$.versions.node||o$.versions.bun))}return!1}class o5{async format($){let w=await Df(),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:P1.pid,hostname:w(),environment:P1.env.NODE_ENV||"development",platform:P1.platform,version:P1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:P1.env.NODE_ENV||P1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class B8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...aW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new o5,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...w8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...w8};return{...w8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:aW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await Kf(this.config.logDirectory,C5.F_OK|C5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await Ff(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:t$.from($);try{if(!mX(this.currentLogFile))await xW(this.currentLogFile,"",{mode:420});if(X=V5(this.currentLogFile,"a",420),Gf(X,W,{flag:"a"}),I5(X),X!==void 0)kW(X),X=void 0;if((await k1(this.currentLogFile)).size===0){if(await xW(this.currentLogFile,W,{flag:"w",mode:420}),(await k1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{kW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return x1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return x1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return x1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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 w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return DW(16).toString("hex")}generateKey(){return DW(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=DW(16),A=Bf("aes-256-gcm",w,Y),X=t$.isBuffer($)?$:t$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=t$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=y5(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(t$.from(t$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await k1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await k1(Y).catch(()=>null))try{if(await Q5(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await dX(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await xW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await k1(Y).catch(()=>null))await Q5(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await gX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await dX(x1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=M5($),A=zf(w),X=y5();await Ef(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),mX(this.currentLogFile))try{let $=V5(this.currentLogFile,"r+");I5($),kW($)}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 w=(await gX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await dX(x1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof x.env.NO_COLOR<"u",w=x.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=x.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${c.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),w}supportsHyperlinks(){if(H0())return!1;let $=x.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=x.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Nf(w)||w.startsWith("./")||w.startsWith("../"))w=qf(w);else return null;return mX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":BG[$],K=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:c.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:c.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
|
|
143
|
-
`);for(let q of
|
|
144
|
-
`;if(
|
|
145
|
-
`;if(
|
|
146
|
-
`);if(this[
|
|
147
|
-
`,
|
|
148
|
-
`),
|
|
149
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(
|
|
150
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
151
|
-
`)}finishProgressBar(
|
|
130
|
+
-----END ${$}-----
|
|
131
|
+
`}function RQ(){let w=S1.randomBytes(20);return w[0]=w[0]&127||1,w}function J2(w=2048){let{privateKey:$,publicKey:Y}=S1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function hE(w){let $=w.export({type:"spki",format:"der"});return S1.createHash("sha1").update($).digest()}function U2(w){let $={serialNumber:w.serialNumber||RQ(),notBefore:w.notBefore,notAfter:w.notAfter,subject:w.subject,issuer:w.issuer||w.subject,publicKey:w.publicKey,extensions:{basicConstraints:{isCA:w.isCA??!1,critical:!0,pathLenConstraint:w.pathLenConstraint},subjectKeyIdentifier:hE(w.publicKey)}};if(w.keyUsage)$.extensions.keyUsage={...w.keyUsage,critical:!0};if(w.extendedKeyUsage)$.extensions.extendedKeyUsage=w.extendedKeyUsage;if(w.subjectAltName?.length)$.extensions.subjectAltName=w.subjectAltName;let Y=SE($),A=ZE(Y,w.signingKey);return{certificate:kE(A,"CERTIFICATE"),certificateDer:A}}function Q2(w){return w.export({type:"pkcs8",format:"pem"})}function DE(w){return S1.createPrivateKey(w)}function xE(w){let $=new S1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
|
|
132
|
+
`);for(let J of X){let[U,...W]=J.split("="),Q=W.join("=");if(U&&Q)A.push({shortName:U.trim(),value:Q.trim()})}return{publicKey:Y,subject:A}}async function MQ(w={}){L("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||fw.DEFAULT_KEY_SIZE;L("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=J2($),X=[{shortName:"C",value:w.countryName||z0.countryName},{shortName:"ST",value:w.stateName||z0.stateName},{shortName:"L",value:w.localityName||z0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=HQ({validityYears:w.validityYears||fw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:W}=U2({serialNumber:RQ(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Q2(Y),notBefore:J,notAfter:U}}async function IQ(w){if(L("ca","Generating new certificate",w.verbose),L("ca",`Options: ${uX(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=xE(w.rootCA.certificate),Y=DE(w.rootCA.privateKey);L("ca",`Generating ${fw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=fw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=J2(A),U=w.commonName||w2(w),W=w.certificateAttributes||[{shortName:"C",value:w.countryName||z0.countryName},{shortName:"ST",value:w.stateName||z0.stateName},{shortName:"L",value:w.localityName||z0.localityName},{shortName:"O",value:w.organizationName||z0.organizationName},{shortName:"CN",value:U}],{notBefore:Q,notAfter:B}=HQ({validityDays:w.validityDays||fw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),j=$2(w),z=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},G=w.extKeyUsage||{serverAuth:!0},{certificate:K}=U2({serialNumber:RQ(),notBefore:Q,notAfter:B,subject:W,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:G,subjectAltName:j});return{certificate:K,privateKey:Q2(X),notBefore:Q,notAfter:B}}function W2(w,$){L(_.STORAGE,`Storing certificate and private key with options: ${uX($)}`,$?.verbose);let{certPath:Y,keyPath:A}=fQ({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});L(_.STORAGE,`Certificate path: ${Y}`,$?.verbose),L(_.STORAGE,`Private key path: ${A}`,$?.verbose);let X=QQ.dirname(Y);if(!ow.existsSync(X))L(_.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),ow.mkdirSync(X,{recursive:!0});L(_.STORAGE,"Writing certificate file",$?.verbose),ow.writeFileSync(Y,w.certificate);let J=QQ.dirname(A);if(!ow.existsSync(J))L(_.STORAGE,`Creating private key directory: ${J}`,$?.verbose),ow.mkdirSync(J,{recursive:!0});return L(_.STORAGE,"Writing private key file",$?.verbose),ow.writeFileSync(A,w.privateKey),L(_.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function B2(w,$){L(_.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=fQ({basePath:$?.basePath,caCertPath:$?.caCertPath});L(_.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=QQ.dirname(Y);if(!ow.existsSync(A))L(_.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),ow.mkdirSync(A,{recursive:!0});return L(_.STORAGE,"Writing CA certificate file",$?.verbose),ow.writeFileSync(Y,w),L(_.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function cX(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=oz(w);return new PE.X509Certificate($)}function vX(w){return cX(w).fingerprint256.replace(/:/g,"").toUpperCase()}function VQ(w){return j2(cX(w).subject)}function bE(w){let $=[],Y=w.split(`
|
|
133
|
+
`);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function j2(w){return bE(w).find(($)=>$.shortName==="CN")?.value||""}function uE(w){let $=[],Y=j2(w.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))$.push(Y);let A=w.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))$.push(J.slice(4))}return[...new Set($)]}function CQ(w,$){let Y=cX(w),A=uE(Y);for(let X of A){if(X===$)return!0;if(X.startsWith("*.")){let J=X.slice(2);if($.endsWith(J)&&$.indexOf(".")===$.lastIndexOf("."))return!0}}return!1}async function vE(w,$){if(kX.platform()!=="darwin")return!1;try{let Y=vX(w);if(!Y)return L(_.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(cE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
134
|
+
`).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return L(_.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return L(_.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return L(_.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function yQ(w,$,Y){L(_.TRUST,`Adding certificate to system trust store with options: ${uX(Y)}`,Y?.verbose),L(_.TRUST,"Storing certificate and private key",Y?.verbose);let A=W2(w,Y);L(_.TRUST,"Storing CA certificate",Y?.verbose);let X=B2($,Y),J=kX.platform();L(_.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=dE[J];if(!U){let W=`Unsupported platform: ${J}`;throw L(_.TRUST,`Error: ${W}`,Y?.verbose),Error(W)}return await U.addCertificate(X,Y),L(_.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var mF,e9=30000,hX,Xz="https://acme-staging-v02.api.letsencrypt.org/directory",Jz="https://acme-v02.api.letsencrypt.org/directory",qX,rF="1.2.840.10045.2.1",tF="1.2.840.10045.3.1.7",aF="1.2.840.10045.4.3.2",sF="2.5.4.3",oF="1.2.840.113549.1.9.14",eF="2.5.29.17",RX,BQ,dq,lq=(w)=>w,pq=(w,$)=>{for(var Y in $)dq(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:nq.bind($,Y)})},rq=(w,$)=>()=>(w&&($=w(w=0)),$),Tz,Oz,L1,OY,Lz,RN,MN,b9,zX,tU,Z0,s,IN,u9,VN,c9,CN,yN,bU,ON,v9,i9,uU,LN,_N,SN,ZN,GX,_z,kN,k0,hN,DN,m9,KX,aU,T0,c,xN,g9,PN,d9,bN,uN,cU,cN,l9,n9,vN,vU,iN,mN,gN,dN,lN,FX,Sz,nN,pN="0.15.6",e0,yX,VY,sU,oU,OX,eU,wQ,CY,$Q,YQ,f$,Zz,kz,Tw,ew,hz,Dz,rN,aN,xz,LX,t3,V0,m,a3,oN,s3,eN,o3,e3,p9,wC,wE,$E,$C,r9,YC,AC,XC,JC,UC,iU,YE,QC,Rw,bz,_X,uz,cz,EQ,vz,iz,SX,mz,gz,_1,BE,rw,WC,BC,jC,az,z0,fw,_,O1,FE,t9="[redacted]",qE,NE,Hw,d0,iE,mE,gE,dE;var z2=t(()=>{mF=iF(import.meta.url);hX=new MY;qX=class qX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};RX=new Nz,BQ=new Ez,dq=Object.defineProperty;Tz={};pq(Tz,{withErrorRecovery:()=>Rz,tryLoadConfig:()=>EN,loadConfigWithResult:()=>qN,loadConfig:()=>yz,isRetryableError:()=>BN,isConfigNotFoundError:()=>WN,isBunfigError:()=>Mz,globalPerformanceMonitor:()=>OY,globalCache:()=>L1,getEnvOrDefault:()=>jN,generateConfigTypes:()=>TN,defaultGeneratedDir:()=>Dz,defaultConfigDir:()=>hz,deepMergeWithArrayStrategy:()=>FQ,deepMerge:()=>Iz,createLibraryConfig:()=>fN,config:()=>NN,bunfigPlugin:()=>HN,applyEnvVarsToConfig:()=>HY,TypeGenerationError:()=>wQ,SchemaValidationError:()=>CY,PluginError:()=>YQ,PerformanceMonitor:()=>zQ,FileSystemError:()=>eU,ErrorFactory:()=>f$,EnvVarError:()=>OX,EnvProcessor:()=>xX,ConfigValidator:()=>qQ,ConfigValidationError:()=>sU,ConfigNotFoundError:()=>yX,ConfigMergeError:()=>oU,ConfigLoader:()=>NQ,ConfigLoadError:()=>VY,ConfigFileLoader:()=>PX,ConfigCache:()=>jQ,CacheUtils:()=>Lz,BunfigError:()=>e0,BrowserConfigError:()=>$Q,ArrayMergeStrategies:()=>Zz});rN=rq(async()=>{Oz=import.meta.require,L1=new jQ,OY=new zQ,Lz={createKey:tq,isEquivalent:aq,estimateMemoryUsage:sq},RN=fX(pU.cwd(),"config"),MN=fX(pU.cwd(),"src/generated"),b9=TX.env.CLARITY_LOG_DIR||jq(wN(),"logs"),zX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:b9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},tU=await $N(),Z0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},s=Z0,IN=Z0.red,u9=Z0.green,VN=Z0.yellow,c9=Z0.blue,CN=Z0.magenta,yN=Z0.cyan,bU=Z0.white,ON=Z0.gray,v9=Z0.bgRed,i9=Z0.bgYellow,uU=Z0.bold,LN=Z0.dim,_N=Z0.italic,SN=Z0.underline,ZN=Z0.reset,GX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_z={debug:"\uD83D\uDD0D",info:c9("ℹ"),success:u9("✓"),warning:i9(bU(uU(" WARN "))),error:v9(bU(uU(" ERROR ")))},kN=new IX("stacks"),k0=new IX("bunfig",{showTags:!0}),hN=m0(IY.cwd(),"config"),DN=m0(IY.cwd(),"src/generated"),m9=EX.env.CLARITY_LOG_DIR||Wq(JN(),"logs"),KX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:m9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},aU=await UN(),T0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=T0,xN=T0.red,g9=T0.green,PN=T0.yellow,d9=T0.blue,bN=T0.magenta,uN=T0.cyan,cU=T0.white,cN=T0.gray,l9=T0.bgRed,n9=T0.bgYellow,vN=T0.bgGray,vU=T0.bold,iN=T0.dim,mN=T0.italic,gN=T0.underline,dN=T0.strikethrough,lN=T0.reset,FX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sz={debug:"\uD83D\uDD0D",info:d9("ℹ"),success:g9("✓"),warning:n9(cU(vU(" WARN "))),error:l9(cU(vU(" ERROR ")))},nN=new CX("stacks"),e0=class extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},yX=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},VY=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},sU=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},oU=class extends e0{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},OX=class extends e0{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},eU=class extends e0{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},wQ=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},CY=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},$Q=class extends e0{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}},YQ=class extends e0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},f$={configNotFound(w,$,Y){return new yX(w,$,Y)},configLoad(w,$,Y){return new VY(w,$,Y)},configValidation(w,$,Y){return new sU(w,$,Y)},configMerge(w,$,Y,A){return new oU(w,$,Y,A)},envVar(w,$,Y,A){return new OX(w,$,Y,A)},fileSystem(w,$,Y){return new eU(w,$,Y)},typeGeneration(w,$,Y){return new wQ(w,$,Y)},schemaValidation(w,$,Y){return new CY(w,$,Y)},browserConfig(w,$,Y,A){return new $Q(w,$,Y,A)},plugin(w,$,Y){return new YQ(w,$,Y)}},Zz={replace:"replace",concat:"concat",smart:"smart"},kz=/^https?:\/\//,Tw=new CX("bunfig",{showTags:!0}),ew=new NQ,hz=g0(v$.cwd(),"config"),Dz=g0(v$.cwd(),"src/generated")});aN=HX.env.CLARITY_LOG_DIR||kq(tN(),"logs"),xz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aN,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},LX={...xz},t3=(async()=>{try{let{loadConfig:w}=await rN().then(()=>Tz),$=await w({name:"clarity",alias:"logging",defaultConfig:xz,cwd:HX.cwd()});if($)Object.assign(LX,$)}catch{}return LX})();V0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=V0,a3=V0.red,oN=V0.green,s3=V0.yellow,eN=V0.blue,o3=V0.magenta,e3=V0.cyan,p9=V0.white,wC=V0.gray,wE=V0.bgRed,$E=V0.bgYellow,$C=V0.bgGray,r9=V0.bold,YC=V0.dim,AC=V0.italic,XC=V0.underline,JC=V0.strikethrough,UC=V0.reset,iU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},YE={debug:"\uD83D\uDD0D",info:eN("ℹ"),success:oN("✓"),warning:$E(p9(r9(" WARN "))),error:wE(p9(r9(" ERROR ")))};QC=new bX("stacks");Rw=class Rw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};bz=class bz extends Rw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};_X=class _X extends Rw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};uz=class uz extends Rw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};cz=class cz extends Rw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};EQ=class EQ extends Rw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};vz=class vz extends Rw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};iz=class iz extends Rw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};SX=class SX extends Rw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};mz=class mz extends Rw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};gz=class gz extends Rw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};_1={configNotFound(w,$,Y){return new bz(w,$,Y)},configLoad(w,$,Y){return new _X(w,$,Y)},configValidation(w,$,Y){return new uz(w,$,Y)},configMerge(w,$,Y,A){return new cz(w,$,Y,A)},envVar(w,$,Y,A){return new EQ(w,$,Y,A)},fileSystem(w,$,Y){return new vz(w,$,Y)},typeGeneration(w,$,Y){return new iz(w,$,Y)},schemaValidation(w,$,Y){return new SX(w,$,Y)},browserConfig(w,$,Y,A){return new mz(w,$,Y,A)},plugin(w,$,Y){return new gz(w,$,Y)}};BE=/^https?:\/\//;rw=new bX("bunfig",{showTags:!0});WC=new tz;BC=Ww(DX.cwd(),"config"),jC=Ww(DX.cwd(),"src/generated"),az={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:MU.join(RU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:MU.join(RU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:MU.join(RU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=az,fw={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"},_={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},O1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};FE=KE(zE);qE=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),NE=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Hw={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},d0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};iE={platform:"darwin",async addCertificate(w,$){if(await vE(w,$?.verbose)){L(_.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),O1.success("Certificate is already trusted in system keychain");return}L(_.TRUST,"Adding certificate to macOS keychain",$?.verbose),await T$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await T$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),L(_.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},mE={platform:"win32",async addCertificate(w,$){L(_.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await T$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await T$(`certutil -delstore -enterprise Root "${A}"`),L(_.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},gE={platform:"linux",async addCertificate(w,$){L(_.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=kX.homedir(),A=fw.LINUX_CERT_DB_FILENAME,X=fw.LINUX_TRUST_ARGS;L(_.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=JQ(Y,A);if(J.length===0){O1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){L(_.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{L(_.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,$?.verbose),await T$(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(W){L(_.TRUST,`Warning: Error deleting existing cert: ${W}`,$?.verbose),console.warn(`Error deleting existing cert: ${W}`)}L(_.TRUST,`Adding new certificate to ${U}`,$?.verbose),await T$(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${w}`),O1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=kX.homedir(),J=fw.LINUX_CERT_DB_FILENAME;L(_.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=JQ(X,J);if(U.length===0){O1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){L(_.TRUST,`Processing certificate database in ${W}`,$?.verbose);try{await T$(`certutil -d sql:${W} -D -n "${A}"`),O1.info(`Cert removed from ${W}`)}catch(Q){L(_.TRUST,`Error removing cert from ${W}: ${Q}`,$?.verbose),console.warn(`Error removing cert from ${W}: ${Q}`)}}}},dE={darwin:iE,win32:mE,linux:gE}});var iX=t(()=>{z2()});import{homedir as OQ}from"node:os";import{join as LQ,resolve as Uy}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",nE,_Q;var SQ=t(()=>{FU();nE={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:LQ(OQ(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:LQ(OQ(),".stacks","ssl","stacks.localhost.crt"),keyPath:LQ(OQ(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},_Q=nE});function i$(w){try{return vX(w)}catch{return null}}function ZQ(w){try{return VQ(w)||null}catch{return null}}function mX(w,$){try{return $.every((Y)=>CQ(w,Y))}catch{return!1}}var gX=t(()=>{iX()});import{existsSync as G2,statSync as K2}from"fs";import{existsSync as aQ,mkdirSync as oE,readdirSync as eE,writeFileSync as wT}from"fs";import{homedir as Z1}from"os";import{dirname as F2,resolve as n0}from"path";import m$ from"process";import{join as $T,relative as YT,resolve as q2}from"path";import U8 from"process";import{existsSync as s2,mkdirSync as fy,readdirSync as Hy,writeFileSync as Ry}from"fs";import{homedir as kQ}from"os";import{dirname as Vy,resolve as l0}from"path";import _Y from"process";import{join as AT,relative as XT,resolve as N2}from"path";import Q8 from"process";import{existsSync as o2,mkdirSync as _y,readdirSync as Sy,writeFileSync as Zy}from"fs";import{dirname as hy,resolve as W8}from"path";import sQ from"process";import{Buffer as R$}from"buffer";import{createCipheriv as JT,createDecipheriv as UT,randomBytes as hQ}from"crypto";import{closeSync as DQ,createReadStream as E2,createWriteStream as QT,existsSync as xQ,fsyncSync as T2,openSync as f2,writeFileSync as WT}from"fs";import{access as BT,constants as H2,mkdir as jT,readdir as dX,rename as R2,stat as k1,unlink as lX,writeFile as PQ}from"fs/promises";import{join as h1}from"path";import h0 from"process";import{pipeline as zT}from"stream/promises";import{createGzip as M2}from"zlib";import D1 from"process";import Y$ from"process";import{Buffer as w$}from"buffer";import{createCipheriv as GT,createDecipheriv as KT,randomBytes as bQ}from"crypto";import{closeSync as uQ,createReadStream as I2,createWriteStream as FT,existsSync as nX,fsyncSync as V2,openSync as C2,writeFileSync as qT}from"fs";import{access as NT,constants as y2,mkdir as ET,readdir as pX,rename as O2,stat as x1,unlink as rX,writeFile as cQ}from"fs/promises";import{isAbsolute as TT,join as P1,resolve as fT}from"path";import x from"process";import{pipeline as HT}from"stream/promises";import{createGzip as L2}from"zlib";import b1 from"process";import A$ from"process";import tX from"process";import{existsSync as aX}from"fs";import{resolve as vQ}from"path";import{existsSync as RT}from"fs";import{existsSync as MT,readdirSync as IT}from"fs";import{extname as iQ,resolve as _2}from"path";import VT from"process";import{join as Cf,relative as yf,resolve as i2}from"path";import q8 from"process";import{Buffer as $$}from"buffer";import{createCipheriv as _f,createDecipheriv as Sf,randomBytes as nQ}from"crypto";import{closeSync as pQ,createReadStream as m2,createWriteStream as Zf,existsSync as oX,fsyncSync as g2,openSync as d2,writeFileSync as kf}from"fs";import{access as hf,constants as l2,mkdir as Df,readdir as eX,rename as n2,stat as u1,unlink as w8,writeFile as rQ}from"fs/promises";import{isAbsolute as xf,join as c1,resolve as Pf}from"path";import P from"process";import{pipeline as bf}from"stream/promises";import{createGzip as p2}from"zlib";import v1 from"process";import X$ from"process";function tE(w,$){this[w]=rE.bind(null,$)}class QW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!G2(w))return!0;return K2(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=G2(Y)?K2(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class WW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function CT(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function yT(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function OT(w){return w.getStats().size*2}function BW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&Y0($[0])&&"id"in $[0]&&$[0].id===3&&Y0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(Y0($)&&Y0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(Y0(w)&&"arr"in w&&Array.isArray(w.arr)&&Y0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&Y0($[0])&&Y0(w[0])){let A=[...$];for(let X of w)if(Y0(X)&&"name"in X){if(!A.find((U)=>Y0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((U)=>Y0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>B8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!Y0($)||!Y0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=BW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((Q)=>Y0(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((Q)=>Y0(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>B8(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function B8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!B8(w[Y],$[Y]))return!1;return!0}if(Y0(w)&&Y0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!B8(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function LT(w,$){if(!o2(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return BW($,A)}catch{return null}}catch{return null}}async function _T({name:w="",cwd:$,defaultConfig:Y}){let A=$||sQ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=W8(A,`${U}${W}`),B=await LT(Q,Y);if(B!==null)return B}try{let U=W8(A,"package.json");if(o2(U)){let Q=(await import(U))[w];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return BW(Y,Q)}catch{}}}catch{}return Y}function ST(w,$={}){let Y=Q8.cwd();while(Y.includes("storage"))Y=N2(Y,"..");let A=N2(Y,w||"");if($?.relative)return XT(Q8.cwd(),A);return A}async function ZT(){try{let w=await _T({name:"clarity",defaultConfig:Y8,cwd:Q8.cwd(),endpoint:"",headers:{}});return{...Y8,...w}}catch{return Y8}}function W0(){if(Y$.env.NODE_ENV==="test"||Y$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kT(){if(Y$.env.NODE_ENV==="test"||Y$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Y$<"u"){let w=Y$.type;if(w==="renderer"||w==="worker")return!1;return!!(Y$.versions&&(Y$.versions.node||Y$.versions.bun))}return!1}class e2{async format(w){let $=await kT(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:D1.pid,hostname:$(),environment:D1.env.NODE_ENV||"development",platform:D1.platform,version:D1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D1.env.NODE_ENV||D1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class j8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...eQ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new e2,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??h0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...A8,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...A8};return{...A8,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:eQ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await BT(this.config.logDirectory,H2.F_OK|H2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await jT(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:R$.from(w);try{if(!xQ(this.currentLogFile))await PQ(this.currentLogFile,"",{mode:420});if(X=f2(this.currentLogFile,"a",420),WT(X,Q,{flag:"a"}),T2(X),X!==void 0)DQ(X),X=void 0;if((await k1(this.currentLogFile)).size===0){if(await PQ(this.currentLogFile,Q,{flag:"w",mode:420}),(await k1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{DQ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return h1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return h1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return h1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return hQ(16).toString("hex")}generateKey(){return hQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=hQ(16),A=JT("aes-256-gcm",$,Y),X=R$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:R$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=M2(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(R$.from(R$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await k1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await dX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await k1(Y).catch(()=>null))try{if(await R2(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await lX(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await PQ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await k1(Y).catch(()=>null))await R2(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await dX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await lX(h1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=E2(w),A=QT($),X=M2();await zT(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),xQ(this.currentLogFile))try{let w=f2(this.currentLogFile,"r+");T2(w),DQ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await dX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await lX(h1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=h0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${o.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let B=BG[w],j=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:o.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:o.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
|
|
135
|
+
`);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
|
|
136
|
+
`;if(W)Q+=`${W}
|
|
137
|
+
`;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:o.blue("◐"),tag:Y,message:`${o.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
138
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let j=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:o.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!W0())console.error(B.trim());await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new j8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(W0())throw Error("createReadStream is not supported in browser environments");if(!xQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return E2(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=R$.isBuffer(w)?w:R$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=UT("aes-256-gcm",Y,X);return W.setAuthTag(J),R$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W0()}isServerMode(){return!W0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!W0()){let J=w.split(`
|
|
139
|
+
`),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:o.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(Q),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
|
|
140
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();h0.stdin.removeListener("data",Y);try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!1)}catch{}h0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!0)}catch{}h0.stdin.resume(),h0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}if(this.fancy&&!W0()){let U=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",W=o.blue("◐");console.error(`${W} ${U} ${o.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
141
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),W!==void 0)this.activeProgressBar.message=W;let Q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Q)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())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||W0())return;h0.stdout.write(`${"\r".padEnd(h0.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||W0()||!h0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?o.green("✓"):o.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=h0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,h0.stdout.write(w.lastRenderedLine),$)h0.stdout.write(`
|
|
142
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await dX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=h1(this.config.logDirectory,A);if(w.before)try{if((await k1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await lX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function $8(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&r($[0])&&"id"in $[0]&&$[0].id===3&&r($[1])&&"id"in $[1]&&$[1].id===4)return $;if(r($)&&r(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(r(w)&&"arr"in w&&Array.isArray(w.arr)&&r($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&r($[0])&&r(w[0])){let A=[...$];for(let X of w)if(r(X)&&"name"in X){if(!A.find((U)=>r(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((U)=>r(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>z8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!r($)||!r(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=$8(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&r(X[0])&&r(Y[A][0])){let J=[...X];for(let U of Y[A])if(r(U)&&"name"in U){if(!J.find((Q)=>r(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((Q)=>r(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>z8(W,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function jW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:$8(w,$);if(Array.isArray(w))return Y==="replace"?$:$8(w,$);if(!r($)||!r(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=$8(U,J);else if(r(J)&&r(U))A[X]=jW(U,J,Y);else A[X]=J}return A}function z8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!z8(w[Y],$[Y]))return!1;return!0}if(r(w)&&r($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!z8(w[X],$[X]))return!1}return!0}return!1}function r(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function sX(w,$,Y="replace"){if(!s2(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return jW($,X,Y)}catch{return null}}catch{return null}}function hT(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)x0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=_Y.env[K]||_Y.env[E];if(q!==void 0){if(Y)x0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function DT({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?hT(w,X,J):X,B=Y||_Y.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)x0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,l0(B,"config"),l0(B,".config"),A?l0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)x0.info(`Searching for configuration in: ${N}`);let R=[l0(B,"config"),l0(B,".config")].concat(A?[l0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let y of R)for(let V of j){let T=l0(N,`${y}${V}`),M=await sX(T,Q,W);if(M!==null){if(J)x0.success(`Configuration loaded from: ${T}`);return M}}}if(w){let N=l0(kQ(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)x0.info(`Checking user config directory: ${N}`);for(let R of f)for(let y of j){let V=l0(N,`${R}${y}`),T=await sX(V,Q,W);if(T!==null){if(J)x0.success(`Configuration loaded from user config directory: ${V}`);return T}}}if(w){let N=l0(kQ(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)x0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let y of j){let V=l0(N,`${R}${y}`),T=await sX(V,Q,W);if(T!==null){if(J)x0.success(`Configuration loaded from user config directory dotfile: ${V}`);return T}}}if(w){let N=kQ(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)x0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let y of j){let V=l0(N,`${R}${y}`),T=await sX(V,Q,W);if(T!==null){if(J)x0.success(`Configuration loaded from user home directory: ${V}`);return T}}}try{let N=l0(B,"package.json");if(s2(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)x0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)x0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return jW(Q,R,W)}catch(y){if(J)x0.warn("Failed to merge package.json config:",y)}}}catch(N){if(J)x0.warn("Failed to load package.json:",N)}if(J)x0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function xT(w,$={}){let Y=U8.cwd();while(Y.includes("storage"))Y=q2(Y,"..");let A=q2(Y,w||"");if($?.relative)return YT(U8.cwd(),A);return A}async function PT(){try{let w=await DT({name:"clarity",alias:"logging",defaultConfig:X8,cwd:U8.cwd()});return{...X8,...w||{}}}catch{return X8}}function H0(){if(A$.env.NODE_ENV==="test"||A$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bT(){if(A$.env.NODE_ENV==="test"||A$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof A$<"u"){let w=A$.type;if(w==="renderer"||w==="worker")return!1;return!!(A$.versions&&(A$.versions.node||A$.versions.bun))}return!1}class wG{async format(w){let $=await bT(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:b1.pid,hostname:$(),environment:b1.env.NODE_ENV||"development",platform:b1.platform,version:b1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:b1.env.NODE_ENV||b1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class G8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...wW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new wG,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...J8,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...J8};return{...J8,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:wW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await NT(this.config.logDirectory,y2.F_OK|y2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await ET(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:w$.from(w);try{if(!nX(this.currentLogFile))await cQ(this.currentLogFile,"",{mode:420});if(X=C2(this.currentLogFile,"a",420),qT(X,Q,{flag:"a"}),V2(X),X!==void 0)uQ(X),X=void 0;if((await x1(this.currentLogFile)).size===0){if(await cQ(this.currentLogFile,Q,{flag:"w",mode:420}),(await x1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{uQ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return P1(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 P1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return P1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return bQ(16).toString("hex")}generateKey(){return bQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=bQ(16),A=GT("aes-256-gcm",$,Y),X=w$.isBuffer(w)?w:w$.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=w$.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=L2(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(w$.from(w$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await x1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await pX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await x1(Y).catch(()=>null))try{if(await O2(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await rX(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await cQ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await x1(Y).catch(()=>null))await O2(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await pX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await rX(P1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=I2(w),A=FT($),X=L2();await HT(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),nX(this.currentLogFile))try{let w=C2(this.currentLogFile,"r+");V2(w),uQ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await pX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await rX(P1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?v.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=x.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${v.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(TT($)||$.startsWith("./")||$.startsWith("../"))$=fT($);else return null;return nX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":jG[w],G=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:v.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:v.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
|
|
143
|
+
`);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
|
|
144
|
+
`;if(W)j+=`${W}
|
|
145
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!H0()&&x.stdout.isTTY)x.stdout.write(`
|
|
146
|
+
`);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":v.blue("◐"),tag:Y,message:`${v.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
147
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":v.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new G8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!nX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return I2(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=w$.isBuffer(w)?w:w$.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=KT("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=w$.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H0()}isServerMode(){return!H0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
|
|
148
|
+
`),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(j),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
149
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(H0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${v.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x.stdin.removeListener("data",Y);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${B}${Q} ${v.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
150
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=v.green("━".repeat(A)),U=v.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?v.green("✓"):v.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=x.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,x.stdout.write(w.lastRenderedLine),$)x.stdout.write(`
|
|
151
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await pX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=P1(this.config.logDirectory,A);if(w.before)try{if((await x1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await rX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function $G(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function YG(w){return w instanceof Yw}function uT(w){return w instanceof K8}function cT(w){if(YG(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class E8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return kY.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=tX.env[Q]||(B?tX.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=tX.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof F8)throw z;throw M$.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw M$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(tX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
152
152
|
|
|
153
|
-
`;for(let A of
|
|
153
|
+
`;for(let A of w)Y+=`${A.key}
|
|
154
154
|
`,Y+=` Type: ${A.type}
|
|
155
155
|
`,Y+=` Description: ${A.description}
|
|
156
156
|
`,Y+=` Example: ${A.example}
|
|
157
157
|
|
|
158
|
-
`;return Y}formatAsMarkdown(
|
|
158
|
+
`;return Y}formatAsMarkdown(w,$){let Y=`# Environment Variables for ${$}
|
|
159
159
|
|
|
160
160
|
`;Y+=`| Variable | Type | Description | Example |
|
|
161
161
|
`,Y+=`|----------|------|-------------|----------|
|
|
162
|
-
`;for(let A of
|
|
163
|
-
`;return Y}}function Pf($,w){let Y=JG("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function wG($,w,Y={}){return YG($,w,Y,new WeakMap)}function YG($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return AG($,w,X,A);if(!j$(w)||!j$($))return w;return cf($,w,Y,A)}function AG($,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 bf($,w);case"smart":return uf($,w,A);default:return w}return w}function bf($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>rW(X,A)))Y.push(A);return Y}function uf($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(j$(w[0])&&j$($[0]))return vf($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function vf($,w,Y){let A=[...w];for(let X of $){if(!j$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>j$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function cf($,w,Y,A){let X=w;if(j$(X)&&A.has(X))return A.get(X);let J={...$};if(j$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(j$(B)&&j$(W))J[U]=YG(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=AG(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function W9($,w,Y="replace"){return wG($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function rW($,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(!rW($[Y],w[Y]))return!1;return!0}if(j$($)&&j$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!rW($[X],w[X]))return!1}return!0}return!1}function j$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class N8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=c1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!nX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new LY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new LY($,Error("Configuration must export a valid object"),"unknown");let E={config:W9(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)c1.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?fw.configLoad($,j):fw.configLoad($,Error(String(j)))}};if(U)return SY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(PW(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return e5(async()=>{return nX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!nX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=PW($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=PW($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!nX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class B9{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await SY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!Tf(w))throw new _Y(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new _Y(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],X=[];return this.validateObjectAgainstSchema($,w,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema($,w,Y,A,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:zG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class j9{fileLoader=new N8;envProcessor=new F8;validator=new B9;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!j)B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)f$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw f$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||vw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(n0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw fw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?yY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)f$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)f$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?yY($,Y,X):Y,B=[n0(S1(),".config",$),n0(S1(),".config"),S1()];for(let W of B){if(X)f$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)f$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?yY($,A,J):A;try{let W=n0(Y,"package.json");if(!nW(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)f$.success(`Configuration loaded from package.json: ${G}`);return{config:W9(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)f$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:yY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw fw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return c1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);c1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,n0($,"config"),n0($,".config"),w?n0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(n0(Y,"package.json")),X}getLocalSearchPaths($,w,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[n0(S1(),".config",$),n0(S1(),".config"),S1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function L5($){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 mf($){return $w.loadConfig({...$,__strictErrorHandling:!0})}async function XG($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await $w.loadConfig($);else A=await $w.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)f$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await $w.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function gf($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await $w.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"&&L5(Y)))return(await $w.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await $w.loadConfig({...$,cwd:$.cwd||vw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&L5(w)))return(await $w.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function df($,w,Y="replace"){let A=new N8;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function yY($,w,Y=!1){let A=new F8,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=vw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function lf($){let w=n0(vw.cwd(),$.configDir),Y=n0(vw.cwd(),$.generatedDir),A=n0(Y,"config-types.ts");if(!nW(K5(A)))rT(K5(A),{recursive:!0,mode:511});let X=nW(w)?tT(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${RH}
|
|
162
|
+
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
163
|
+
`;return Y}}function vT(w,$){let Y=QG("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function AG(w,$,Y={}){return XG(w,$,Y,new WeakMap)}function XG(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return JG(w,$,X,A);if(!zw($)||!zw(w))return $;return dT(w,$,Y,A)}function JG(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return iT(w,$);case"smart":return mT(w,$,A);default:return $}return $}function iT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>oQ(X,A)))Y.push(A);return Y}function mT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return gT(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function gT(w,$,Y){let A=[...$];for(let X of w){if(!zw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((B)=>zw(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function dT(w,$,Y,A){let X=$;if(zw(X)&&A.has(X))return A.get(X);let J={...w};if(zw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(zw(W)&&zw(Q))J[U]=XG(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=JG(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function zW(w,$,Y="replace"){return AG(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function oQ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!oQ(w[Y],$[Y]))return!1;return!0}if(zw(w)&&zw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!oQ(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class T8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=Y;if(X){let B=i1.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!aX(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new SY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new SY(w,Error("Configuration must export a valid object"),"unknown");let N={config:zW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)i1.setWithFileCheck("file",N,w,J);return N}catch(B){throw B instanceof Error?M$.configLoad(w,B):M$.configLoad(w,Error(String(B)))}};if(U)return kY.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(vQ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return $G(async()=>{return aX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!aX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=vQ(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=vQ(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!aX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class GW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await kY.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!RT($))throw new ZY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new ZY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:GG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class KW{fileLoader=new T8;envProcessor=new E8;validator=new GW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)Mw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){let Q=Date.now()-$;throw Mw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||m$.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(n0(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw M$.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?LY(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)Mw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)Mw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?LY(w,Y,X):Y,W=[n0(Z1(),".config",w),n0(Z1(),".config"),Z1()];for(let Q of W){if(X)Mw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)Mw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?LY(w,A,J):A;try{let Q=n0(Y,"package.json");if(!aQ(Q))return null;let B=await import(Q),j=B[w],z=w;if(!j&&$)j=B[$],z=$;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)Mw.success(`Configuration loaded from package.json: ${z}`);return{config:zW(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)Mw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:LY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw M$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return i1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);i1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,n0(w,"config"),n0(w,".config"),$?n0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(n0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[n0(Z1(),".config",w),n0(Z1(),".config"),Z1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function S2(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function lT(w){return J$.loadConfig({...w,__strictErrorHandling:!0})}async function UG(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await J$.loadConfig(w);else A=await J$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Mw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await J$.applyEnvironmentVariables(W.name||"",$,!0,W.verbose||!1))?.config??$;return $}}async function nT(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await J$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&S2(Y)))return(await J$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await J$.loadConfig({...w,cwd:w.cwd||m$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&S2($)))return(await J$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function pT(w,$,Y="replace"){let A=new T8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function LY(w,$,Y=!1){let A=new E8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=m$.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function rT(w){let $=n0(m$.cwd(),w.configDir),Y=n0(m$.cwd(),w.generatedDir),A=n0(Y,"config-types.ts");if(!aQ(F2(A)))oE(F2(A),{recursive:!0,mode:511});let X=aQ($)?eE($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${If}
|
|
164
164
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
165
|
-
`;
|
|
166
|
-
${X.map((
|
|
165
|
+
`;wT(A,J,{mode:438})}function tT(w){let $=null,Y=null,A=()=>{if(!Y)Y=UG(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Mw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let W=X[U];return A(),W},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,W){if(!$)$={...X};return $[U]=W,!0}})}function aT(w){let $=_2(VT.cwd(),w?.configDir||"./config");function Y(){if(!MT($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=IT($).filter((Q)=>X.has(iQ(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),W=new Map;for(let{base:Q,file:B}of U){let j=iQ(B).toLowerCase(),z=W.get(Q);if(!z){W.set(Q,B);continue}let G=iQ(z).toLowerCase();if(J.indexOf(j)<J.indexOf(G))W.set(Q,B)}return Array.from(W.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function A(){let X=Y(),J=X.map((B)=>B.base),U=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",W=X.length?`{
|
|
166
|
+
${X.map((B)=>{let j=_2($,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
|
|
167
167
|
`)}
|
|
168
168
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
169
|
-
export type ConfigByName = ${
|
|
169
|
+
export type ConfigByName = ${W}
|
|
170
170
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
171
171
|
export type ConfigOf = Config
|
|
172
|
-
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function CH($,w={}){let Y=G8.cwd();while(Y.includes("storage"))Y=v5(Y,"..");let A=v5(Y,$||"");if(w?.relative)return VH(G8.cwd(),A);return A}function M0(){if(e$.env.NODE_ENV==="test"||e$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xH(){if(e$.env.NODE_ENV==="test"||e$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof e$<"u"){let $=e$.type;if($==="renderer"||$==="worker")return!1;return!!(e$.versions&&(e$.versions.node||e$.versions.bun))}return!1}class NG{async format($){let w=await xH(),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:v1.pid,hostname:w(),environment:v1.env.NODE_ENV||"development",platform:v1.platform,version:v1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:v1.env.NODE_ENV||v1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class cw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...K8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new NG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...lW,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lW};return{...lW,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:K8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await SH(this.config.logDirectory,g5.F_OK|g5.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await ZH(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:a$.from($);try{if(!rX(this.currentLogFile))await dW(this.currentLogFile,"",{mode:420});if(X=m5(this.currentLogFile,"a",420),_H(X,W,{flag:"a"}),i5(X),X!==void 0)gW(X),X=void 0;if((await b1(this.currentLogFile)).size===0){if(await dW(this.currentLogFile,W,{flag:"w",mode:420}),(await b1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{gW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return mW(16).toString("hex")}generateKey(){return mW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=mW(16),A=yH("aes-256-gcm",w,Y),X=a$.isBuffer($)?$:a$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=a$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=l5(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(a$.from(a$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let $=await b1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await tX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await b1(Y).catch(()=>null))try{if(await d5(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await aX(B)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await dW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await b1(Y).catch(()=>null))await d5(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await tX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await aX(u1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=c5($),A=LH(w),X=l5();await kH(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),rX(this.currentLogFile))try{let $=m5(this.currentLogFile,"r+");i5($),gW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await tX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await aX(u1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let $=typeof P.env.NO_COLOR<"u",w=P.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=P.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${g.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),w}supportsHyperlinks(){if(M0())return!1;let $=P.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=P.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(hH(w)||w.startsWith("./")||w.startsWith("../"))w=DH(w);else return null;return rX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":cH[$],K=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:g.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:g.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
|
|
173
|
-
`);for(let q of
|
|
174
|
-
`;if(
|
|
175
|
-
`;if(
|
|
176
|
-
`);if(this[
|
|
177
|
-
`,
|
|
178
|
-
`),
|
|
179
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(
|
|
180
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
181
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await tX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=u1(this.config.logDirectory,A);if($.before)try{if((await b1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await aX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var gT,dT=($)=>$,nT=($,w)=>{for(var Y in w)gT($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:lT.bind(w,Y)})},pT=($,w)=>()=>($&&(w=$($=0)),w),r5,JG,c1,SY,UG,rf,tf,_5,oX,tW,D0,o,af,S5,sf,Z5,of,ef,uW,$H,h5,D5,vW,wH,YH,AH,XH,eX,WG,JH,k0,UH,WH,k5,$8,aW,R0,c,BH,x5,jH,P5,zH,GH,cW,KH,b5,u5,FH,iW,NH,qH,EH,TH,fH,w8,BG,HH,RH="0.15.6",$$,j8,LY,sW,oW,z8,eW,$9,_Y,w9,Y9,fw,jG,zG,f$,$w,GG,KG,MH,QH,FG,K8,XO,C0,g,qO,PH,EO,bH,TO,fO,n5,HO,uH,vH,RO,p5,MO,IO,VO,CO,QO,lW,cH,yO;var z9=t(()=>{gT=Object.defineProperty;r5={};nT(r5,{withErrorRecovery:()=>e5,tryLoadConfig:()=>df,loadConfigWithResult:()=>mf,loadConfig:()=>XG,isRetryableError:()=>xf,isConfigNotFoundError:()=>kf,isBunfigError:()=>$G,globalPerformanceMonitor:()=>SY,globalCache:()=>c1,getEnvOrDefault:()=>Pf,generateConfigTypes:()=>lf,defaultGeneratedDir:()=>KG,defaultConfigDir:()=>GG,deepMergeWithArrayStrategy:()=>W9,deepMerge:()=>wG,createLibraryConfig:()=>nf,config:()=>gf,bunfigPlugin:()=>pf,applyEnvVarsToConfig:()=>yY,TypeGenerationError:()=>$9,SchemaValidationError:()=>_Y,PluginError:()=>Y9,PerformanceMonitor:()=>X9,FileSystemError:()=>eW,ErrorFactory:()=>fw,EnvVarError:()=>z8,EnvProcessor:()=>F8,ConfigValidator:()=>B9,ConfigValidationError:()=>sW,ConfigNotFoundError:()=>j8,ConfigMergeError:()=>oW,ConfigLoader:()=>j9,ConfigLoadError:()=>LY,ConfigFileLoader:()=>N8,ConfigCache:()=>A9,CacheUtils:()=>UG,BunfigError:()=>$$,BrowserConfigError:()=>w9,ArrayMergeStrategies:()=>jG});MH=pT(async()=>{JG=import.meta.require,c1=new A9,SY=new X9,UG={createKey:Mf,isEquivalent:If,estimateMemoryUsage:Vf},rf=X8(pW.cwd(),"config"),tf=X8(pW.cwd(),"src/generated"),_5=A8.env.CLARITY_LOG_DIR||eT(yf(),"logs"),oX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},tW=await Of(),D0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},o=D0,af=D0.red,S5=D0.green,sf=D0.yellow,Z5=D0.blue,of=D0.magenta,ef=D0.cyan,uW=D0.white,$H=D0.gray,h5=D0.bgRed,D5=D0.bgYellow,vW=D0.bold,wH=D0.dim,YH=D0.italic,AH=D0.underline,XH=D0.reset,eX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WG={debug:"\uD83D\uDD0D",info:Z5("ℹ"),success:S5("✓"),warning:D5(uW(vW(" WARN "))),error:h5(uW(vW(" ERROR ")))},JH=new U8("stacks"),k0=new U8("bunfig",{showTags:!0}),UH=l0(OY.cwd(),"config"),WH=l0(OY.cwd(),"src/generated"),k5=Y8.env.CLARITY_LOG_DIR||sT(Zf(),"logs"),$8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:k5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},aW=await hf(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=R0,BH=R0.red,x5=R0.green,jH=R0.yellow,P5=R0.blue,zH=R0.magenta,GH=R0.cyan,cW=R0.white,KH=R0.gray,b5=R0.bgRed,u5=R0.bgYellow,FH=R0.bgGray,iW=R0.bold,NH=R0.dim,qH=R0.italic,EH=R0.underline,TH=R0.strikethrough,fH=R0.reset,w8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},BG={debug:"\uD83D\uDD0D",info:P5("ℹ"),success:x5("✓"),warning:u5(cW(iW(" WARN "))),error:b5(cW(iW(" ERROR ")))},HH=new B8("stacks"),$$=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},j8=class extends $${code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},LY=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}},sW=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})}},oW=class extends $${code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},z8=class extends $${code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},eW=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}},$9=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}},_Y=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})}},w9=class extends $${code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},Y9=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}},fw={configNotFound($,w,Y){return new j8($,w,Y)},configLoad($,w,Y){return new LY($,w,Y)},configValidation($,w,Y){return new sW($,w,Y)},configMerge($,w,Y,A){return new oW($,w,Y,A)},envVar($,w,Y,A){return new z8($,w,Y,A)},fileSystem($,w,Y){return new eW($,w,Y)},typeGeneration($,w,Y){return new $9($,w,Y)},schemaValidation($,w,Y){return new _Y($,w,Y)},browserConfig($,w,Y,A){return new w9($,w,Y,A)},plugin($,w,Y){return new Y9($,w,Y)}},jG={replace:"replace",concat:"concat",smart:"smart"},zG=/^https?:\/\//,f$=new B8("bunfig",{showTags:!0}),$w=new j9,GG=n0(vw.cwd(),"config"),KG=n0(vw.cwd(),"src/generated")});QH=G8.env.CLARITY_LOG_DIR||IH(CH(),"logs"),FG={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:QH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},K8={...FG},XO=(async()=>{try{let{loadConfig:$}=await MH().then(()=>r5),w=await $({name:"clarity",alias:"logging",defaultConfig:FG,cwd:G8.cwd()});if(w)Object.assign(K8,w)}catch{}return K8})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},g=C0,qO=C0.red,PH=C0.green,EO=C0.yellow,bH=C0.blue,TO=C0.magenta,fO=C0.cyan,n5=C0.white,HO=C0.gray,uH=C0.bgRed,vH=C0.bgYellow,RO=C0.bgGray,p5=C0.bold,MO=C0.dim,IO=C0.italic,VO=C0.underline,CO=C0.strikethrough,QO=C0.reset,lW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cH={debug:"\uD83D\uDD0D",info:bH("ℹ"),success:PH("✓"),warning:vH(n5(p5(" WARN "))),error:uH(n5(p5(" ERROR ")))};yO=new cw("stacks")});var m1={};EB(m1,{shouldReusePort:()=>i1,safeStringify:()=>H$,safeDeleteFile:()=>N9,resolvePathRewrite:()=>F9,redactSensitive:()=>q8,isValidRootCA:()=>K9,isSingleProxyOptions:()=>ZY,isSingleProxyConfig:()=>nH,isProcessElevated:()=>E8,isMultiProxyOptions:()=>mw,isMultiProxyConfig:()=>TG,getSudoPassword:()=>iw,getPrimaryDomain:()=>T8,extractHostname:()=>lH,execSudoSync:()=>ww,debugLog:()=>N});import{execSync as G9}from"node:child_process";import*as EG from"node:fs/promises";function iw(){return process.env.SUDO_PASSWORD}function E8(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function ww($){if(E8())return G9($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=iw(),Y=$.replace(/'/g,"'\\''");if(w)return G9(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return G9(`sudo -n sh -c '${Y}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function N($,w,Y){if(Y)iH.debug(`[rpx:${$}] ${w}`)}function i1(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function dH($){let w=$.toLowerCase();return mH.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function q8($){if(Array.isArray($))return $.map((Y)=>q8(Y));if(typeof $==="string")return gH.test($)?qG:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(dH(Y)){w[Y]=qG;continue}w[Y]=q8(A)}return w}function H$($,w){return JSON.stringify(q8($),null,w)}function lH($){if(mw($))return $.proxies.map((w)=>{let Y=w.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(ZY($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function K9($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function T8($){if(!$)return"stacks.localhost";if(mw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(ZY($))return $.to||"stacks.localhost";return"stacks.localhost"}function TG($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function mw($){return"proxies"in $&&Array.isArray($.proxies)}function ZY($){return"to"in $&&typeof $.to==="string"}function nH($){return!!($&&("to"in $)&&!("proxies"in $))}function F9($,w){if(!w||w.length===0)return null;for(let Y of w)if($===Y.from||$.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?$.slice(Y.from.length)||"/":$;return{targetHost:A,targetPath:X}}return null}async function N9($,w){try{await EG.unlink($),N("certificates",`Successfully deleted: ${$}`,w)}catch(Y){if(Y.code!=="ENOENT")N("certificates",`Warning: Could not delete ${$}: ${Y}`,w)}}var iH,qG="[redacted]",mH,gH;var X0=t(()=>{z9();iH=new cw("rpx",{showTags:!1});mH=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),gH=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as f8}from"node:child_process";import{homedir as pH}from"node:os";import{join as rH}from"node:path";function H8(){return rH(pH(),"Library/Keychains/login.keychain-db")}function E9(){return[Rw,H8()]}function fG($,w=q9){let Y=f8(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
|
|
182
|
-
`)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function
|
|
183
|
-
`))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return
|
|
172
|
+
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function Of(w,$={}){let Y=q8.cwd();while(Y.includes("storage"))Y=i2(Y,"..");let A=i2(Y,w||"");if($?.relative)return yf(q8.cwd(),A);return A}function M0(){if(X$.env.NODE_ENV==="test"||X$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uf(){if(X$.env.NODE_ENV==="test"||X$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X$<"u"){let w=X$.type;if(w==="renderer"||w==="worker")return!1;return!!(X$.versions&&(X$.versions.node||X$.versions.bun))}return!1}class NG{async format(w){let $=await uf(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:v1.pid,hostname:$(),environment:v1.env.NODE_ENV||"development",platform:v1.platform,version:v1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:v1.env.NODE_ENV||v1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class g${name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...N8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new NG,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...tQ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...tQ};return{...tQ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:N8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await hf(this.config.logDirectory,l2.F_OK|l2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Df(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:$$.from(w);try{if(!oX(this.currentLogFile))await rQ(this.currentLogFile,"",{mode:420});if(X=d2(this.currentLogFile,"a",420),kf(X,Q,{flag:"a"}),g2(X),X!==void 0)pQ(X),X=void 0;if((await u1(this.currentLogFile)).size===0){if(await rQ(this.currentLogFile,Q,{flag:"w",mode:420}),(await u1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(X!==void 0)try{pQ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return c1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return c1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return c1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return nQ(16).toString("hex")}generateKey(){return nQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=nQ(16),A=_f("aes-256-gcm",$,Y),X=$$.isBuffer(w)?w:$$.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=$$.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=p2(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$($$.from($$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await u1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await eX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await u1(Y).catch(()=>null))try{if(await n2(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await w8(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await rQ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await u1(Y).catch(()=>null))await n2(Y,J)}if(this.currentLogFile=A,$.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($.maxFiles))await w8(c1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=m2(w),A=Zf($),X=p2();await bf(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),oX(this.currentLogFile))try{let w=d2(this.currentLogFile,"r+");g2(w),pQ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await eX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await w8(c1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=P.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${g.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(xf($)||$.startsWith("./")||$.startsWith("../"))$=Pf($);else return null;return oX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":df[w],G=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:g.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:g.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
|
|
173
|
+
`);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
|
|
174
|
+
`;if(W)j+=`${W}
|
|
175
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
|
|
176
|
+
`);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:Y,message:`${g.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
177
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":g.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new g$($,{...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(!oX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return m2(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=$$.isBuffer(w)?w:$$.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=Sf("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=$$.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
|
|
178
|
+
`),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(j),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
179
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(M0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${g.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();P.stdin.removeListener("data",Y);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${B}${Q} ${g.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
180
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?g.green("✓"):g.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=P.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,P.stdout.write(w.lastRenderedLine),$)P.stdout.write(`
|
|
181
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await eX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=c1(this.config.logDirectory,A);if(w.before)try{if((await u1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await w8(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var pE,rE=(w)=>w,aE=(w,$)=>{for(var Y in $)pE(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:tE.bind($,Y)})},sE=(w,$)=>()=>(w&&($=w(w=0)),$),a2,QG,i1,kY,WG,sT,oT,Z2,Y8,eQ,D0,o,eT,k2,wf,h2,$f,Yf,mQ,Af,D2,x2,gQ,Xf,Jf,Uf,Qf,A8,BG,Wf,x0,Bf,jf,P2,X8,wW,R0,v,zf,b2,Gf,u2,Kf,Ff,dQ,qf,c2,v2,Nf,lQ,Ef,Tf,ff,Hf,Rf,J8,jG,Mf,If="0.15.6",Yw,K8,SY,$W,YW,F8,AW,XW,ZY,JW,UW,M$,zG,GG,Mw,J$,KG,FG,Vf,Lf,qG,N8,jO,C0,g,RO,cf,MO,vf,IO,VO,r2,CO,mf,gf,yO,t2,OO,LO,_O,SO,ZO,tQ,df,kO;var FW=t(()=>{pE=Object.defineProperty;a2={};aE(a2,{withErrorRecovery:()=>$G,tryLoadConfig:()=>pT,loadConfigWithResult:()=>lT,loadConfig:()=>UG,isRetryableError:()=>cT,isConfigNotFoundError:()=>uT,isBunfigError:()=>YG,globalPerformanceMonitor:()=>kY,globalCache:()=>i1,getEnvOrDefault:()=>vT,generateConfigTypes:()=>rT,defaultGeneratedDir:()=>FG,defaultConfigDir:()=>KG,deepMergeWithArrayStrategy:()=>zW,deepMerge:()=>AG,createLibraryConfig:()=>tT,config:()=>nT,bunfigPlugin:()=>aT,applyEnvVarsToConfig:()=>LY,TypeGenerationError:()=>XW,SchemaValidationError:()=>ZY,PluginError:()=>UW,PerformanceMonitor:()=>WW,FileSystemError:()=>AW,ErrorFactory:()=>M$,EnvVarError:()=>F8,EnvProcessor:()=>E8,ConfigValidator:()=>GW,ConfigValidationError:()=>$W,ConfigNotFoundError:()=>K8,ConfigMergeError:()=>YW,ConfigLoader:()=>KW,ConfigLoadError:()=>SY,ConfigFileLoader:()=>T8,ConfigCache:()=>QW,CacheUtils:()=>WG,BunfigError:()=>Yw,BrowserConfigError:()=>JW,ArrayMergeStrategies:()=>zG});Vf=sE(async()=>{QG=import.meta.require,i1=new QW,kY=new WW,WG={createKey:CT,isEquivalent:yT,estimateMemoryUsage:OT},sT=W8(sQ.cwd(),"config"),oT=W8(sQ.cwd(),"src/generated"),Z2=Q8.env.CLARITY_LOG_DIR||AT(ST(),"logs"),Y8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Z2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},eQ=await ZT(),D0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=D0,eT=D0.red,k2=D0.green,wf=D0.yellow,h2=D0.blue,$f=D0.magenta,Yf=D0.cyan,mQ=D0.white,Af=D0.gray,D2=D0.bgRed,x2=D0.bgYellow,gQ=D0.bold,Xf=D0.dim,Jf=D0.italic,Uf=D0.underline,Qf=D0.reset,A8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},BG={debug:"\uD83D\uDD0D",info:h2("ℹ"),success:k2("✓"),warning:x2(mQ(gQ(" WARN "))),error:D2(mQ(gQ(" ERROR ")))},Wf=new j8("stacks"),x0=new j8("bunfig",{showTags:!0}),Bf=l0(_Y.cwd(),"config"),jf=l0(_Y.cwd(),"src/generated"),P2=U8.env.CLARITY_LOG_DIR||$T(xT(),"logs"),X8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:P2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},wW=await PT(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=R0,zf=R0.red,b2=R0.green,Gf=R0.yellow,u2=R0.blue,Kf=R0.magenta,Ff=R0.cyan,dQ=R0.white,qf=R0.gray,c2=R0.bgRed,v2=R0.bgYellow,Nf=R0.bgGray,lQ=R0.bold,Ef=R0.dim,Tf=R0.italic,ff=R0.underline,Hf=R0.strikethrough,Rf=R0.reset,J8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jG={debug:"\uD83D\uDD0D",info:u2("ℹ"),success:b2("✓"),warning:v2(dQ(lQ(" WARN "))),error:c2(dQ(lQ(" ERROR ")))},Mf=new G8("stacks"),Yw=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},K8=class extends Yw{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},SY=class extends Yw{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},$W=class extends Yw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},YW=class extends Yw{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},F8=class extends Yw{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},AW=class extends Yw{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},XW=class extends Yw{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},ZY=class extends Yw{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},JW=class extends Yw{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},UW=class extends Yw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},M$={configNotFound(w,$,Y){return new K8(w,$,Y)},configLoad(w,$,Y){return new SY(w,$,Y)},configValidation(w,$,Y){return new $W(w,$,Y)},configMerge(w,$,Y,A){return new YW(w,$,Y,A)},envVar(w,$,Y,A){return new F8(w,$,Y,A)},fileSystem(w,$,Y){return new AW(w,$,Y)},typeGeneration(w,$,Y){return new XW(w,$,Y)},schemaValidation(w,$,Y){return new ZY(w,$,Y)},browserConfig(w,$,Y,A){return new JW(w,$,Y,A)},plugin(w,$,Y){return new UW(w,$,Y)}},zG={replace:"replace",concat:"concat",smart:"smart"},GG=/^https?:\/\//,Mw=new G8("bunfig",{showTags:!0}),J$=new KW,KG=n0(m$.cwd(),"config"),FG=n0(m$.cwd(),"src/generated")});Lf=q8.env.CLARITY_LOG_DIR||Cf(Of(),"logs"),qG={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},N8={...qG},jO=(async()=>{try{let{loadConfig:w}=await Vf().then(()=>a2),$=await w({name:"clarity",alias:"logging",defaultConfig:qG,cwd:q8.cwd()});if($)Object.assign(N8,$)}catch{}return N8})();C0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},g=C0,RO=C0.red,cf=C0.green,MO=C0.yellow,vf=C0.blue,IO=C0.magenta,VO=C0.cyan,r2=C0.white,CO=C0.gray,mf=C0.bgRed,gf=C0.bgYellow,yO=C0.bgGray,t2=C0.bold,OO=C0.dim,LO=C0.italic,_O=C0.underline,SO=C0.strikethrough,ZO=C0.reset,tQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},df={debug:"\uD83D\uDD0D",info:vf("ℹ"),success:cf("✓"),warning:gf(r2(t2(" WARN "))),error:mf(r2(t2(" ERROR ")))};kO=new g$("stacks")});var g1={};EB(g1,{shouldReusePort:()=>m1,safeStringify:()=>Iw,safeDeleteFile:()=>EW,resolvePathRewrite:()=>NW,redactSensitive:()=>H8,isValidRootCA:()=>qW,isSingleProxyOptions:()=>DY,isSingleProxyConfig:()=>sf,isProcessElevated:()=>hY,isMultiProxyOptions:()=>d$,isMultiProxyConfig:()=>fG,getSudoPassword:()=>I$,getPrimaryDomain:()=>R8,extractHostname:()=>af,execSudoSync:()=>U$,debugLog:()=>F,authorizeSystemAccess:()=>nf});import{execSync as f8}from"node:child_process";import*as TG from"node:fs/promises";function I$(){return process.env.SUDO_PASSWORD}function hY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function nf(w={}){if(process.platform==="win32")return!0;if(hY()||!!I$())return!0;let $=w.exec??f8;try{return $("sudo -n true",{stdio:"ignore"}),!0}catch{if(!w.interactive)return!1}try{return $("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function U$(w){if(hY())return f8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=I$(),Y=w.replace(/'/g,"'\\''");if($)return f8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return f8(`sudo -n sh -c '${Y}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function F(w,$,Y){if(Y)lf.debug(`[rpx:${w}] ${$}`)}function m1(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function tf(w){let $=w.toLowerCase();return pf.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function H8(w){if(Array.isArray(w))return w.map((Y)=>H8(Y));if(typeof w==="string")return rf.test(w)?EG:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(tf(Y)){$[Y]=EG;continue}$[Y]=H8(A)}return $}function Iw(w,$){return JSON.stringify(H8(w),null,$)}function af(w){if(d$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(DY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function qW(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function R8(w){if(!w)return"stacks.localhost";if(d$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(DY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function fG(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function d$(w){return"proxies"in w&&Array.isArray(w.proxies)}function DY(w){return"to"in w&&typeof w.to==="string"}function sf(w){return!!(w&&("to"in w)&&!("proxies"in w))}function NW(w,$){if(!$||$.length===0)return null;for(let Y of $)if(w===Y.from||w.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?w.slice(Y.from.length)||"/":w;return{targetHost:A,targetPath:X}}return null}async function EW(w,$){try{await TG.unlink(w),F("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")F("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var lf,EG="[redacted]",pf,rf;var X0=t(()=>{FW();lf=new g$("rpx",{showTags:!1});pf=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),rf=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as M8}from"node:child_process";import{homedir as of}from"node:os";import{join as ef}from"node:path";function I8(){return ef(of(),"Library/Keychains/login.keychain-db")}function fW(){return[C$,I8()]}function HG(w,$=TW){let Y=M8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
|
|
182
|
+
`)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function HW(w){if(process.platform!=="darwin")return;let $=i$(w.caPath);if(!$)return;let Y=w.commonName??TW,A=w.keychains??fW();for(let X of A)for(let J of HG(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))U$(`security delete-certificate -Z ${J} "${X}"`);else M8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});F("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function RW(w,$,Y){if(process.platform!=="darwin")return V8(w,Y);try{let X=M8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return F("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function V8(w,$){let Y=i$(w);if(!Y)return!1;for(let A of fW())try{let X=M8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
|
|
183
|
+
`))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return F("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var V$="-d -r trustRoot -p ssl -p basic",C$="/Library/Keychains/System.keychain",TW="rpx.localhost";var MW=t(()=>{gX();X0()});import{execSync as IW}from"node:child_process";import G0 from"node:fs/promises";import*as VW from"node:os";import{homedir as d1}from"node:os";import*as IG from"node:path";import{join as K0}from"node:path";import*as y$ from"node:process";function CW(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function yW(w,$,Y){let A=K0(d1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:C8,keyPath:K0(A,"rpx.localhost.key"),caCertPath:K0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function VG(w){return{caCertPath:K0(w,$H),caKeyPath:K0(w,YH)}}async function AH(w,$){try{let[Y,A]=await Promise.all([G0.readFile(w.caCertPath,"utf8"),G0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return F("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return F("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function RG(w){let $=new Set;$.add(w);let Y=w.split(".");if(Y.length>=3){let A=Y[Y.length-1],X=Y[Y.length-2],J=new Set(["co","com","org","net","ac","gov","edu"]);if(!(Y.length===3&&A.length===2&&J.has(X)))$.add(`*.${Y.slice(1).join(".")}`)}return Array.from($)}function CG(w){let Y=R8(w).replace(/\*/g,"wildcard"),A=K0(d1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||K0(X,`${Y}.ca.crt`),certPath:w.https.certPath||K0(X,`${Y}.crt`),keyPath:w.https.keyPath||K0(X,`${Y}.key`)};return{caCertPath:K0(X,`${Y}.ca.crt`),certPath:K0(X,`${Y}.crt`),keyPath:K0(X,`${Y}.key`)}}function MG(w){let $=new Set;if(d$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";RG(A).forEach((X)=>$.add(X))});else if(DY(w)){let Y=w.to||"rpx.localhost";RG(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function l1(w){if(O$&&!w.forceRegenerate){F("ssl","Using cached SSL configuration",w.verbose);return}y8();let $=d$(w)?w.proxies.map((j)=>j.to):[w.to];F("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=xY(w,w.verbose),A=Y.basePath||K0(d1(),".stacks","ssl");await G0.mkdir(A,{recursive:!0});let X=VG(A),J=await AH(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await MQ(Y);try{await Promise.all([G0.writeFile(X.caCertPath,J.certificate),G0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,F("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(j){throw F("ssl",`Error saving Root CA files: ${j}`,w.verbose),Error(`Failed to save Root CA files: ${j}`)}}else F("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let W=await IQ({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([G0.writeFile(Y.certPath,W.certificate),G0.writeFile(Y.keyPath,W.privateKey),G0.writeFile(Y.caCertPath,J.certificate)]),F("ssl","Certificate files saved successfully",w.verbose)}catch(j){throw F("ssl",`Error saving certificate files: ${j}`,w.verbose),Error(`Failed to save certificate files: ${j}`)}if(U?!1:await OG(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(F("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(O$={key:W.privateKey,cert:W.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(y$.platform==="darwin")try{HW({caPath:X.caCertPath,verbose:w.verbose});let j=I8();try{IW(`security add-trusted-cert ${V$} -k "${j}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(U$(`security add-trusted-cert ${V$} -k ${C$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");B=!0;let z=K0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
|
|
184
184
|
echo "Trusting RPX Root CA"
|
|
185
185
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
186
186
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
187
187
|
if [ -n "$SUDO_PASSWORD" ]
|
|
188
188
|
then
|
|
189
189
|
printf '%s
|
|
190
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
190
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${V$} -k ${C$} "${X.caCertPath}"
|
|
191
191
|
else
|
|
192
|
-
sudo security add-trusted-cert ${
|
|
192
|
+
sudo security add-trusted-cert ${V$} -k ${C$} "${X.caCertPath}"
|
|
193
193
|
fi
|
|
194
194
|
echo "Root CA trusted! Please restart your browser."
|
|
195
195
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
196
|
-
`;await G0.writeFile(G,
|
|
196
|
+
`;await G0.writeFile(z,G,{mode:493})}catch(j){if(w.verbose)H.warn(`Could not add Root CA to trust store automatically: ${j}`);let z=K0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
|
|
197
197
|
echo "Trusting RPX Root CA"
|
|
198
198
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
199
199
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
200
200
|
if [ -n "$SUDO_PASSWORD" ]
|
|
201
201
|
then
|
|
202
202
|
printf '%s
|
|
203
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
203
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${V$} -k ${C$} "${X.caCertPath}"
|
|
204
204
|
else
|
|
205
|
-
sudo security add-trusted-cert ${
|
|
205
|
+
sudo security add-trusted-cert ${V$} -k ${C$} "${X.caCertPath}"
|
|
206
206
|
fi
|
|
207
207
|
echo "Root CA trusted! Please restart your browser."
|
|
208
208
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
209
|
-
`;if(await G0.writeFile(G,
|
|
209
|
+
`;if(await G0.writeFile(z,G,{mode:493}),w.verbose)H.info(`Created a trust helper script at: ${z}`),H.info(`If you're still having certificate issues, run: sh ${z}`)}else if(y$.platform==="linux")try{let{exec:j}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",G=`
|
|
210
210
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
211
211
|
cp "${X.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
212
212
|
update-ca-certificates
|
|
213
213
|
echo "RPX Root CA installed. Please restart your browser."
|
|
214
|
-
`,
|
|
214
|
+
`,K=K0(VW.tmpdir(),`rpx-trust-${Date.now()}.sh`);await G0.writeFile(K,G,{mode:493}),await new Promise((E)=>{j(`sudo bash "${K}"`,(q)=>{if(q){if(w.verbose)H.warn(`Could not trust certificates: ${q}`);E(!1)}else{if(w.verbose)H.success("Successfully added certificates to system trust store");E(!0)}})}),await G0.unlink(K).catch(()=>{}),B=!0}catch(j){if(w.verbose)H.warn(`Failed to trust certificates: ${j}`)}else if(y$.platform==="win32")try{let j=`
|
|
215
215
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${X.caCertPath.replace(/\//g,"\\")}")
|
|
216
216
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
217
217
|
$store.Open("ReadWrite")
|
|
218
218
|
$store.Add($cert)
|
|
219
219
|
$store.Close()
|
|
220
220
|
Write-Host "Root CA trusted successfully!"
|
|
221
|
-
`,
|
|
222
|
-
`)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue
|
|
223
|
-
`),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),
|
|
224
|
-
`,q);if(
|
|
221
|
+
`,z=K0(VW.tmpdir(),"rpx-trust.ps1");if(await G0.writeFile(z,j),IW(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");B=!0}catch(j){if(w.verbose)H.warn(`Could not trust certificate: ${j}`)}else try{await yQ(W,J.certificate,Y),B=!0}catch(j){if(w.verbose)H.warn(`Could not add certificate to trust store: ${j}`)}if(O$={key:W.privateKey,cert:W.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!B&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function y8(){O$=null}async function Q$(w){if(!w)return null;if(O$)return O$;let $=xY(w);try{let[Y,A,X]=await Promise.all([G0.access($.keyPath).then(()=>!0).catch(()=>!1),G0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?G0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return F("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,W=J?U!==!1:!0;F("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${W}`,w.verbose);let Q=$.basePath||K0(d1(),".stacks","ssl"),B=VG(Q);if(!(W?await OG(B.caCertPath,w):!0))return F("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,G,K]=await Promise.all([G0.readFile($.keyPath,"utf8"),G0.readFile($.certPath,"utf8"),X&&$.caCertPath?G0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(K&&!K.includes("-----BEGIN CERTIFICATE-----"))return F("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(d$(w))try{let{X509Certificate:E}=await import("node:crypto"),N=new E(G).subjectAltName||"",R=w.proxies.map((y)=>y.to).filter((y)=>!N.includes(`DNS:${y}`));if(R.length>0)return F("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(E){F("ssl",`Could not verify cert SANs: ${E}`,w.verbose)}return F("ssl","Successfully loaded existing certificates",w.verbose),O$={key:z,cert:G,ca:K},O$}catch(Y){return F("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function xY(w,$){let Y=R8(w);F("ssl",`Primary domain: ${Y}`,$);let A=CG(w),X=K0(d1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(MG(w)).map((W)=>({type:2,value:W}))};if(qW(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(MG(w)).map((J)=>({type:2,value:J}))}}async function yG(w,$){let Y=CG({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];F("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>EW(X,$)))}async function OG(w,$){try{if(F("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),y$.platform==="darwin"){if($?.serverName)return RW(w,$.serverName,{verbose:$?.verbose});return V8(w,{verbose:$?.verbose})}else if(y$.platform==="win32")try{let Y=ZQ(w)||"";if(!Y)return F("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(IW(A).toString().includes(Y))return F("ssl","Certificate found in trusted root store",$?.verbose),!0;return F("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return F("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(y$.platform==="linux")try{let Y=i$(w);if(!Y)return F("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await G0.readdir(X)}catch{continue}for(let U of J){let W=i$(IG.join(X,U));if(W&&W===Y)return F("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return F("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return F("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return F("ssl",`Platform ${y$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return F("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var O$=null,C8,$H="rpx-root-ca.crt",YH="rpx-root-ca.key";var O8=t(()=>{iX();lw();SQ();MW();X0();MW();gX();gX();C8=K0(d1(),".stacks","ssl","rpx.localhost.crt")});function XH(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function JH(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function OW(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function L$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function n1(w,$){return{upstreams:JH(w),strategy:$?.strategy??"round-robin",healthCheck:XH($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function UH(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function QH(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function WH(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function BH(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function LG(w){let $=UH(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return WH(w,$);case"least-connections":return BH($);case"round-robin":default:return QH(w,$)}}function L8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function PY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function jH(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function zH(w,$){let{hostname:Y,port:A}=jH($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),L8(w,$)}catch{PY(w,$)}finally{clearTimeout(J)}}function p1(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)zH(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function l$(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as SG,timingSafeEqual as _G}from"node:crypto";import{readFileSync as GH}from"node:fs";function bY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return _G(Y,Y),!1;return _G(Y,A)}function FH(w,$){let Y=(G)=>SG("md5").update(G).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let G=A.length;G>0;G-=16)U.push(J.subarray(0,Math.min(G,16)));for(let G=A.length;G>0;G>>=1)U.push(G&1?Buffer.from([0]):A.subarray(0,1));let W=Y(Buffer.concat(U));for(let G=0;G<1000;G++){let K=[];if(K.push(G&1?A:W.subarray(0,16)),G%3)K.push(X);if(G%7)K.push(A);K.push(G&1?W.subarray(0,16):A),W=Y(Buffer.concat(K))}let Q="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",B=(G,K)=>{let E="",q=G;for(let N=0;N<K;N++)E+=Q[q&63],q>>=6;return E},j=W,z="";return z+=B(j[0]<<16|j[6]<<8|j[12],4),z+=B(j[1]<<16|j[7]<<8|j[13],4),z+=B(j[2]<<16|j[8]<<8|j[14],4),z+=B(j[3]<<16|j[9]<<8|j[15],4),z+=B(j[4]<<16|j[10]<<8|j[5],4),z+=B(j[11],2),`$apr1$${$}$${z}`}function qH(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return bY(FH(w,A),$)}if($.startsWith("{SHA}")){let Y=SG("sha1").update(w,"utf8").digest("base64");return bY(`{SHA}${Y}`,$)}return bY(w,$)}function NH(w){let $=new Map;for(let Y of w.split(`
|
|
222
|
+
`)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function r1(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=NH(GH(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let W=!1;for(let Q of Y)if(bY(J,Q.username)&&bY(U,Q.password))W=!0;if(A){let Q=A.get(J);if(Q&&qH(U,Q))W=!0}return W}}}function ZG(w,$,Y){if($.startsWith(KH))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let Q="";try{Q=Buffer.from(U,"base64").toString("utf8")}catch{Q=""}let B=Q.indexOf(":");if(B>=0&&Y.verify(Q.slice(0,B),Q.slice(B+1)))return}let W=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${W}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var KH="/.well-known/acme-challenge/";var uY=()=>{};function fH(w){return TH.has(w.toUpperCase())}function HH(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function RH(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function MH(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function IH(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function VH(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class PG{socket=null;buf=new Uint8Array(CH);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw _8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>yH)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=OH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class bG{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=HH();maxWaiters;checkoutIdleMs=MH();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=RH(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new PG;return EH({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=IH();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw n$;let w=await this.waitForSlot();if(w===n$)throw n$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(n$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(LW,this.checkoutIdleMs):LW;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-LW;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&S8.get(this.key)===this)S8.delete(this.key)}}}function kH(w,$){let Y=S8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new bG(X,J,$,w),S8.set(w,Y)}return Y}function kG(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function hH(w,$,Y){let A=xG.decode(w.subarray($,Y)),X=A.indexOf(`\r
|
|
223
|
+
`),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),W=Number.parseInt(J.slice(U+1,U+5),10),Q=J.startsWith("HTTP/1.0"),B=[],j=-1,z=!1,G=Q,K=!1,E=!1,q=X===-1?A.length:X+2;while(q<A.length){let N=A.indexOf(`\r
|
|
224
|
+
`,q);if(N===-1)N=A.length;let f=A.slice(q,N);if(q=N+2,f==="")continue;let R=f.indexOf(":");if(R===-1)continue;let y=f.slice(0,R),V=f.slice(R+1).trim(),T=y.charCodeAt(0)|32;if(T===99||T===116||T===107){let M=y.toLowerCase();if(M==="content-length"){let O=/^\d+$/.test(V)?Number(V):Number.NaN;if(!Number.isSafeInteger(O)||j>=0&&j!==O)E=!0;else j=O;continue}if(M==="transfer-encoding"){if(V.toLowerCase().includes("chunked"))z=!0;continue}if(M==="connection"){let O=V.toLowerCase();if(O.includes("close"))G=!0;if(O.includes("keep-alive"))K=!0;continue}if(M==="keep-alive")continue}B.push([y,V])}if(Q&&K)G=!1;if(z&&j>=0)j=-1;return{status:W,headerEnd:Y,headers:B,contentLength:j,chunked:z,closeConn:G,malformed:E}}function DH(w,$){return $||w===204||w===304}async function uG(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:W}=w,Q=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw cY;let B=null;if(W){let K=X.get("content-length"),E=K?Number.parseInt(K,10):Number.NaN;if(Number.isNaN(E)||E>hG)throw cY;if(B=await iH(W),B===null)throw cY}let j=vH(Y,A,X,$,J,U,B),z=j;if(B&&B.length)z=new Uint8Array(j.length+B.length),z.set(j),z.set(B,j.length);let G=kH($,w.maxPerHost??VH());for(let K=0;;K++){if(K>0)await new Promise((q)=>{setTimeout(q,K)});let E;try{E=G.acquireIdleSync()??await G.acquireOrDial()}catch(q){if(q!==n$&&K<4)continue;throw q}try{let q=E.socket.write(z);if(q<z.length)await E.writeAll(z.subarray(q));return await PH(G,E,Q)}catch(q){let N=q===_8&&K<4&&(E.fresh||fH(Y));if(G.destroy(E),N)continue;if(q===_8)throw Error("upstream closed connection");throw q}}}async function xH(w){let $=kG(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw _W;if(w.len===w.pos)throw _8;throw Error("upstream closed mid-header")}if(w.len-w.pos>DG)throw Error("upstream header block too large");await w.waitForData(w.len),$=kG(w.buf,w.len,w.pos)}return $}async function PH(w,$,Y){let A;for(;;){let J=await xH($);if(A=hH($.buf,$.pos,J),$.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let X=A.headers;if(DH(A.status,Y))return cG(w,$,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(cH(w,$,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if($.len-$.pos>=A.contentLength){let U=$.pos+A.contentLength,W=$.len>U,Q=null;if(A.contentLength>=LH)Q=$.buf.subarray($.pos,U),$.buf=new Uint8Array(_H);else if(A.contentLength>0)Q=$.buf.slice($.pos,U);if($.pos=0,$.len=0,A.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:A.status,headers:X})}return new Response(bH(w,$,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(uH($),{status:A.status,headers:X})}function cG(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function bH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(W)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);W.close()};return new ReadableStream({start(W){if(J)W.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(W)},async pull(W){for(;;){let Q=$.bodyQueue;if(Q&&Q.length>0){let B=Q.shift();if($.queuedBytes-=B.length,$.resumeIfDrained(),W.enqueue(B),$.bodyRemaining===0&&Q.length===0)U(W);return}if($.bodyRemaining===0){if($.bodyQueue)U(W);return}if($.closed){$.bodyQueue=null,w.destroy($),W.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function uH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function cH(w,$,Y){$.streamingBody=!0;let A=0,X=!1;async function J(){for(;;){for(let U=$.pos;U+1<$.len;U++)if($.buf[U]===13&&$.buf[U+1]===10){let W=xG.decode($.buf.subarray($.pos,U));return $.pos=U+2,W}if($.closed)throw Error("upstream closed mid-chunk-header");if($.len-$.pos>DG)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({async pull(U){for(;;){if(A>0){if($.len===$.pos){if($.closed){w.destroy($),U.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let j=Math.min(A,$.len-$.pos);if(U.enqueue($.buf.slice($.pos,$.pos+j)),$.pos+=j,A-=j,$.resumeIfDrained(),A===0)X=!0;return}if(X)await J(),X=!1;let W=await J(),Q=W.indexOf(";"),B=Number.parseInt(Q===-1?W:W.slice(0,Q),16);if(!Number.isInteger(B)||B<0){w.destroy($),U.error(Error("upstream sent malformed chunk size"));return}if(B===0){for(;;)if(await J()==="")break;cG(w,$,Y),U.close();return}A=B}},cancel(){w.destroy($)}})}function vH(w,$,Y,A,X,J,U){let W=`${w} ${$} HTTP/1.1\r
|
|
225
225
|
host: ${A}\r
|
|
226
226
|
x-forwarded-for: 127.0.0.1\r
|
|
227
227
|
x-forwarded-proto: https\r
|
|
228
228
|
x-forwarded-host: ${X}\r
|
|
229
|
-
`;if(J!==void 0)
|
|
230
|
-
`;let
|
|
231
|
-
`}if(
|
|
232
|
-
`,U&&!W
|
|
233
|
-
`;return
|
|
234
|
-
`,QR.encode(B)}async function PR($){let w=$.getReader(),Y=[],A=0;for(;;){let{done:U,value:B}=await w.read();if(U)break;if(B){if(A+=B.length,A>ZG)return w.cancel().catch(()=>{}),null;Y.push(B)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var KR,PY,Q8,FR,y9,dw,ZG=1048576,Q9=30000,RR=16384,hG=262144,MR=2097152,IR=524288,VR=8192,CR=4096,QR,DG,yR,y8;var uG=t(()=>{({connect:KR}=Bun),PY=Symbol("rpx.pool.fallback"),Q8=Symbol("rpx.pool.stale"),FR=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);y9=Symbol("rpx.pool.timeout"),dw=Symbol("rpx.pool.busy");QR=new TextEncoder,DG=new TextDecoder,yR=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);y8=new Map});function vG($){let w=typeof $==="string"?{to:$}:$,Y=(w.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:w.status??301,preservePath:w.preservePath??!0}}function cG($,w,Y){if(!$.preservePath)return $.to||"/";let A=`${w}${Y}`;return A==="/"?`${$.to}/`:`${$.to}${A}`}import*as z$ from"node:path";function bY($,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 uR($){let w=z$.extname($).toLowerCase();return bR[w]??"application/octet-stream"}function vR($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let Y=z$.posix.normalize(`/${w}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function cR($,w){let Y=vR($);if(Y===null)return null;let A=z$.posix.extname(Y);if(w.cleanUrls&&A===".html"){let X=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:z$.join(w.dir,Y),redirectTo:X||"/"}}if(Y===""||$.endsWith("/"))return{filePath:z$.join(w.dir,Y,"index.html")};if(A!=="")return{filePath:z$.join(w.dir,Y)};if(w.pathRewriteStyle==="flat")return{filePath:z$.join(w.dir,`${Y}.html`)};return{filePath:z$.join(w.dir,Y,"index.html")}}async function iG($,w){let Y=cR($,w);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":uR(Y.filePath),"Cache-Control":A}});if(w.spa){let J=z$.join(w.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var bR;var uY=t(()=>{bR={".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 iR(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function gR($){let w=$.headers.get("host")||"",Y=w.indexOf(":");return Y===-1?w:w.slice(0,Y)}function dG($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let Y=$.slice(w.length);return Y===""?"/":Y}return $}function mG($){if($.upstreamPool)return yG($.upstreamPool);if($.sourceHost)return{url:$.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function gG($,w,Y,A){let X=Y?.url??w.sourceHost??"",U=w.stripBasePathPrefix??!1?dG($,w.basePath):$,B=F9(U,w.pathRewrites);if(B)X=B.targetHost,U=B.targetPath,N("request",`Path rewrite: ${$} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function dR($){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 r1($,w,Y){let A=async(X,J)=>{let{pathname:U,search:B}=dR(X.url),W=gR(X),j=$(W,U);if(!j&&Y){let E=await Y(W,U,X);if(E instanceof Response)return E;if(E&&E.retry)j=$(W,U)}if(!j)return N("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(j.auth){let E=_G(X,U,j.auth);if(E)return N("request",`401 challenge for ${W}${U}`,w),E}if(j.redirect){let E=cG(j.redirect,U,B);return N("request",`${j.redirect.status} redirect ${W}${U} → ${E}`,w),new Response(null,{status:j.redirect.status,headers:{location:E}})}if(j.static){let H=j.stripBasePathPrefix??!0?dG(U,j.basePath):U;return iG(H,j.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let E=mG(j);if(!J||!E)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:H,targetPath:M}=gG(U,j,E,w),y=`ws://${H}${M}${B}`,C={};for(let[L,Z]of X.headers)if(!mR.has(L.toLowerCase())&&L.toLowerCase()!=="host")C[L]=Z;C.host=H,C["x-forwarded-for"]="127.0.0.1",C["x-forwarded-proto"]="https",C["x-forwarded-host"]=W;let f={targetUrl:y,forwardHeaders:C};if(J.upgrade(X,{data:f})){N("ws",`upgraded ${W}${M} → ${y}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}let z=mG(j);if(!z)return new Response(`No upstream configured for ${W}`,{status:502});if(j.cleanUrls&&U.endsWith(".html")){let E=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:E}})}let{targetHost:G,targetPath:K}=gG(U,j,z,w),F=j.changeOrigin?`http://${G}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",q=j.upstreamPool;if(q)z.activeConnections++;try{let E=await PG({hostPort:G,method:X.method,path:`${K}${B}`,reqHeaders:X.headers,forwardedHost:W,originOverride:F,body:X.body});if(q)C8(q,z);return E}catch(E){if(E===y9){if(N("request",`Upstream timeout for ${W}`,w),q)DY(q,z);return new Response("Gateway Timeout",{status:504})}if(E===dw)return N("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(E===PY||!T)try{let H=new Headers(X.headers);if(H.set("host",G),H.set("x-forwarded-for","127.0.0.1"),H.set("x-forwarded-proto","https"),H.set("x-forwarded-host",W),F!==void 0)H.set("origin",F);let M=await fetch(`http://${G}${K}${B}`,{method:X.method,headers:H,body:X.body,redirect:"manual"});if(q)C8(q,z);return M}catch(H){if(N("request",`Proxy error for ${W}: ${H}`,w),q)DY(q,z);return new Response(`Proxy Error: ${H}`,{status:502})}if(N("request",`Proxy error for ${W}: ${E}`,w),q)DY(q,z);return new Response(`Proxy Error: ${E}`,{status:502})}finally{if(q)z.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return N("request",`Unhandled proxy handler error: ${U}`,w),new Response("Bad Gateway",{status:502})}}}function t1($){let w=new WeakMap,Y=iR();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){N("ws",`failed to open upstream ${X}: ${W}`,$),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let B={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};w.set(A,B),U.addEventListener("open",()=>{B.upstreamOpen=!0;for(let W of B.pending)U.send(W);B.pending=[],B.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{N("ws",`upstream error for ${X}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=w.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let B=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+B>Y){N("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,$);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}w.delete(A);return}J.pending.push(U),J.pendingBytes+=B},close(A,X,J){let U=w.get(A);if(!U)return;w.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var mR;var O8=t(()=>{xY();uG();uY();X0();mR=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});import*as nG from"node:fs";import*as pG from"node:path";function vY($,w){if(!$||!w.startsWith(lG))return null;let Y=w.slice(lG.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return nG.readFileSync(pG.join($,Y),"utf8")}catch{return null}}var lG="/.well-known/acme-challenge/";var L8=()=>{};function C$($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function lR($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function a1($){let w=new Map;for(let A of $){let X=C$(A.path),J=w.get(A.host);if(!J)J=new Map,w.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of w){let J=[];for(let[U,B]of X)J.push({path:U,route:B});J.sort((U,B)=>B.path.length-U.path.length),Y.set(A,J)}return Y}function _8($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!F1(J))continue;if(EY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}function s1($,w,Y){let A=_8($,w);if(!A)return;for(let X of A)if(lR(Y,X.path))return X.route;return}var cY=()=>{};import*as iY from"node:fs/promises";import*as O9 from"node:path";function nR($){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 pR($,w,Y,A){try{let[X,J]=await Promise.all([iY.readFile(w,"utf8"),iY.readFile(Y,"utf8")]);return{serverName:$,cert:X,key:J}}catch(X){return N("sni",`skipping ${$}: ${X.message}`,A),null}}async function o1($,w){let Y=new Map;if($.certsDir){let X=[];try{X=await iY.readdir($.certsDir)}catch(J){N("sni",`certsDir read failed (${$.certsDir}): ${J.message}`,w)}for(let J of X){let U=nR(J);if(!U)continue;let B=J.slice(0,-4);Y.set(U,{certPath:O9.join($.certsDir,J),keyPath:O9.join($.certsDir,`${B}.key`)})}}if($.domains)for(let[X,J]of Object.entries($.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await pR(X,J.certPath,J.keyPath,w);if(U)A.push(U)}return A}var S8=t(()=>{X0()});import*as Cw from"node:fs/promises";import*as L9 from"node:path";function tR($,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 tG($){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 mY{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??_X,this.issuer=$.issuer??XW,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??rR;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(!tG($))return!1;if(tR($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return N("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;if(!tG($))return!1;let w=this.inFlight.get($);if(w)return w;let Y=this.negativeCache.get($);if(Y!==void 0&&Date.now()<Y)return N("on-demand",`${$} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1;let A=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,A),A}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return N("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),this.cacheNegative($),!1;try{N("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let Y={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,Y),this.negativeCache.delete($),N("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.cacheNegative($),N("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}cacheNegative($){if(this.negativeCache.size>=rG){let w=Date.now();for(let[Y,A]of this.negativeCache)if(A<=w)this.negativeCache.delete(Y);if(this.negativeCache.size>=rG){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set($,Date.now()+this.negativeCacheMs)}async loadFromDisk($){let{certPath:w,keyPath:Y}=this.pathsFor($);try{let[A,X]=await Promise.all([Cw.readFile(w,"utf8"),Cw.readFile(Y,"utf8")]),J={serverName:$,cert:A,key:X};return this.certs.set($,J),N("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:L9.join(this.certsDir,`${$}.crt`),keyPath:L9.join(this.certsDir,`${$}.key`)}}async persist($,w,Y){await Cw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor($);await Promise.all([Cw.writeFile(A,w,"utf8"),Cw.writeFile(X,Y,{encoding:"utf8",mode:384})])}}var rR=60000,rG=4096;var _9=t(()=>{bX();X0()});import{existsSync as aR,readdirSync as ML,readFileSync as sR,statSync as oR}from"node:fs";import{homedir as eR}from"node:os";import{isAbsolute as $M,join as e1}from"node:path";function aG($,w){if($==="~")return w;if($.startsWith("~/"))return e1(w,$.slice(2));return $}function XM($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function sG($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function JM($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function UM($,w){let Y=w.readText(e1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(e1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function WM($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function BM($,w){let Y=UM($,w);if(Y?.command)return WM(Y);let A=w.fileExists(e1($,"buddy")),X=w.readText(e1($,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Z9($,w={}){let Y={dirExists:w.dirExists??S9.dirExists,fileExists:w.fileExists??S9.fileExists,readText:w.readText??S9.readText},A=w.detect??BM,X=w.homeDir??eR(),J=$.tlds??YM,U=($.roots??wM).map((K)=>aG(K,X)),B=$.idleTimeoutMs??AM,W=new Map;for(let K of $.sites??[])W.set(K.to,K);let j=(K)=>K.idleTimeoutMs??B;function z(K){let F=gA(W,K);if(!F)return null;let T=$M(F.dir)?F.dir:aG(F.dir,X),q=F.selfRegisters??!1,E=F.routes??[];if(!q&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let H=oG({...F.env??{}},void 0,K);return{host:K,id:sG(K),dir:T,command:F.command,env:H,routes:E,selfRegisters:q,idleTimeoutMs:j(F),source:"config"}}function G(K){let F=JM(K,J);if(!F)return null;for(let T of U){let q=e1(T,F);if(!Y.dirExists(q))continue;let E=A(q,Y);if(!E)continue;let H=E.selfRegisters??!1;return{host:K,id:sG(K),dir:q,command:E.command,env:oG({...E.env??{}},E.urlEnv,K),routes:H?[]:E.routes??[],selfRegisters:H,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(K){let F=XM(K);if(!F)return null;return z(F)??G(F)}}}function oG($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}var wM,YM,AM=1800000,S9;var h9=t(()=>{wM=["~/Code"],YM=["localhost","test"],S9={dirExists:($)=>{try{return oR($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return aR($)}catch{return!1}},readText:($)=>{try{return sR($,"utf8")}catch{return null}}}});import*as Z8 from"node:net";function Qw($,w,Y){return N("port",`Checking if port ${$} is in use on ${w}`,Y),new Promise((A)=>{let X=Z8.createServer(),J=setTimeout(()=>{N("port",`Checking port ${$} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")N("port",`Port ${$} is in use`,Y),A(!0);else N("port",`Error checking port ${$}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),N("port",`Port ${$} is available`,Y),X.close(),A(!1)});try{X.listen($,w)}catch(U){clearTimeout(J),N("port",`Exception checking port ${$}: ${U}`,Y),A(!0)}})}async function D9($,w,Y,A=50){N("port",`Finding available port starting from ${$} (max attempts: ${A})`,Y);let X=$,J=0;while(J<A){if(J++,!await Qw(X,w,Y))return N("port",`Found available port: ${X} after ${J} attempts`,Y),X;N("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${$}`)}function eG($,w,Y=5000,A){return N("port",`Testing connection to ${w}:${$}`,A),new Promise((X)=>{let J=Z8.connect({host:w,port:$,timeout:Y});J.once("connect",()=>{N("port",`Successfully connected to ${w}:${$}`,A),J.end(),X(!0)}),J.once("timeout",()=>{N("port",`Connection to ${w}:${$} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{N("port",`Failed to connect to ${w}:${$}: ${U.message}`,A),J.destroy(),X(!1)})})}class h8{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,Y=50){this.hostname=$,this.verbose=w,this.maxRetries=Y}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Qw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await eG($,this.hostname,3000,this.verbose))return N("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let Y=await D9($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await eG(Y,this.hostname,3000,this.verbose))if(Y<$+this.maxRetries)return this.findNextAvailablePort(Y+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort($){N("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var OL;var k9=t(()=>{X0();OL=new h8});import*as D8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as jM}from"node:os";import*as x9 from"node:path";import*as k8 from"node:process";function y$(){return x9.join(jM(),".stacks","rpx","registry.d")}function gY($){return typeof $==="string"&&$.length>0&&$.length<=128&&zM.test($)}function P9($,w){if(!gY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return x9.join($,`${w}.json`)}function b0($){if(!Number.isInteger($)||$<=0)return!1;try{return k8.kill($,0),!0}catch(w){return w.code==="EPERM"}}function $6($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0||Array.isArray(w.from)&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&gY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function GM($){await p0.mkdir($,{recursive:!0})}async function x8($,w=y$(),Y){if(!$6($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await GM(w);let A=P9(w,$.id),X=`${A}.tmp.${k8.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function dY($,w=y$(),Y){let A=P9(w,$);try{await p0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function KM($,w=y$(),Y){let A=P9(w,$);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!$6(J))return N("registry",`entry ${$} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return N("registry",`entry ${$} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function Q$($=y$(),w){let Y;try{Y=await p0.readdir($)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!gY(J))continue;let U=await KM(J,$,w);if(U)A.push(U)}return A}async function $Y($=y$(),w){let Y=await Q$($,w),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!b0(X.pid))N("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,w),await dY(X.id,$,w).catch(()=>{}),A++}return A}function lY($,w={}){let Y=w.dir??y$(),A=w.debounceMs??100,X=w.pollMs??Math.max(A*2,250),J=w.verbose;D8.mkdirSync(Y,{recursive:!0});let U=null,B=!1,W=null,j=!1,z=(E)=>{return JSON.stringify(E.map((H)=>({id:H.id,from:H.from,to:H.to,path:H.path,pid:H.pid,pathRewrites:H.pathRewrites,cleanUrls:H.cleanUrls,changeOrigin:H.changeOrigin,static:H.static,loadBalancer:H.loadBalancer})).sort((H,M)=>H.id.localeCompare(M.id)))},G=()=>{if(U=null,B)return;Q$(Y,J).then((E)=>{return W=z(E),$(E)}).catch((E)=>{N("registry",`watcher onChange failed: ${E}`,J)})},K=()=>{if(B)return;if(U)clearTimeout(U);U=setTimeout(G,A)},T=setInterval(()=>{if(B||j)return;j=!0,Q$(Y,J).then((E)=>{if(z(E)!==W)K()}).catch((E)=>{N("registry",`watcher poll failed: ${E}`,J)}).finally(()=>{j=!1})},X),q=D8.watch(Y,{persistent:!0},(E,H)=>{if(H&&/\.tmp\.\d+\.\d+$/.test(H))return;K()});return q.on("error",(E)=>{N("registry",`watcher error: ${E}`,J)}),K(),{close:()=>{if(B=!0,U)clearTimeout(U);clearInterval(T),q.close()}}}var zM;var lw=t(()=>{X0();zM=/^[a-zA-Z0-9._-]+$/});import{closeSync as w6,openSync as FM,readFileSync as NM}from"node:fs";import*as Y6 from"node:fs/promises";import{spawn as qM}from"node:child_process";import{homedir as EM}from"node:os";import*as nY from"node:path";import*as R$ from"node:process";class P8{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor($){this.resolver=$.resolver,this.registryDir=$.registryDir??y$(),this.rpxDir=$.rpxDir??nY.join(EM(),".stacks","rpx"),this.verbose=$.verbose??!1,this.startupTimeoutMs=$.startupTimeoutMs??TM,this.pollIntervalMs=$.pollIntervalMs??fM,this.restartDelayMs=$.restartDelayMs??RM,this.killGraceMs=$.killGraceMs??MM,this.launch=$.launcher??VM(this.verbose),this.probePort=$.probePort??IM,this.pickPort=$.pickPort??((Y)=>D9(Y,"127.0.0.1")),this.isHostRoutable=$.isHostRoutable??(()=>!1),this.onSiteActivating=$.onSiteActivating,this.now=$.now??Date.now,this.writeEntry=$.writeEntry??x8,this.removeEntry=$.removeEntry??dY;let w=$.reapIntervalMs??HM;if(this.reaper=setInterval(()=>{this.reapIdle()},w),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest($){if(this.stopped)return{kind:"unknown"};let w=this.sites.get($);if(w&&w.status==="failed"&&this.now()-w.failedAt>=this.restartDelayMs)this.sites.delete($),w=void 0;if(!w){let Y=this.resolver.resolve($);if(!Y)return{kind:"unknown"};w=await this.start(Y)}if(w.lastAccess=this.now(),w.status==="ready")return{kind:"ready",host:$};if(w.status==="failed")return{kind:"failed",host:$,error:w.error??"failed to start",logTail:this.readLogTail(w)};return{kind:"starting",host:$,sinceMs:this.now()-w.startedAt,source:w.site.source,logTail:this.readLogTail(w,16)}}async start($){try{this.onSiteActivating?.($.host)}catch{}let w=new Map;if(!$.selfRegisters)for(let B of $.routes){if(w.has(B.portEnv))continue;let W=await this.pickPort(B.defaultPort??3000);w.set(B.portEnv,W)}let Y=nY.join(this.rpxDir,"sites",`${$.id}.log`);await Y6.mkdir(nY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv($,w),X=null,J;try{X=this.launch({command:$.command,cwd:$.dir,env:A,logPath:Y})}catch(B){J=`failed to spawn: ${B.message}`}let U={site:$,status:J?"failed":"starting",handle:X,ports:w,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set($.host,U),J)return R.warn(`rpx: site ${$.host} ${J}`),U;return R.info(`rpx: booting ${$.host} → ${$.command} (${$.dir})`),X.exited.then((B)=>this.onProcessExit(U,B)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((B)=>{N("sites",`readiness loop for ${$.host} threw: ${B}`,this.verbose)}),U}async onProcessExit($,w){if($.exited=!0,this.stopped||this.sites.get($.site.host)!==$)return;if($.status==="ready"){R.warn(`rpx: ${$.site.host} exited${w!==null?` (code ${w})`:""} — will reboot on next request`),this.sites.delete($.site.host);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if($.status==="starting")this.fail($,`process exited${w!==null?` with code ${w}`:""} before becoming ready`)}async driveReadiness($){let{site:w}=$,Y=this.now()+this.startupTimeoutMs,A=w.selfRegisters?()=>this.isHostRoutable(w.host):await this.makeGateProbe(w,$.ports);while(this.now()<Y&&!this.stopped){if($.status!=="starting"||$.exited)return;if(await A()){if(await this.publishRoutes($),$.status==="starting")$.status="ready",R.success(`rpx: ${w.host} ready`);return}await b9(this.pollIntervalMs)}if($.status==="starting")this.fail($,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe($,w){let Y=$.routes.filter((X)=>X.readyGate??C$(X.path)==="/").map((X)=>w.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...w.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes($){let{site:w,ports:Y}=$;if(w.selfRegisters||w.routes.length===0)return;let A=w.routes.find((W)=>C$(W.path)==="/")??w.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of w.routes){if(W===A)continue;let j=Y.get(W.portEnv);if(j===void 0)continue;J.push({from:C$(W.path),to:`localhost:${j}`,stripPrefix:W.stripPrefix??!1})}let U={id:w.id,from:`localhost:${X}`,to:w.host,cwd:w.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:$.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),$.routeIds=[w.id];let B=this.now()+2000;while(this.now()<B&&!this.isHostRoutable(w.host))await b9(50)}fail($,w){$.status="failed",$.error=w,$.failedAt=this.now(),R.warn(`rpx: site ${$.site.host} failed — ${w}`),this.killProcess($)}buildEnv($,w){let Y={};for(let[A,X]of Object.entries(R$.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,$.env);for(let[A,X]of w)Y[A]=String(X);return Y.RPX_SITE_HOST=$.host,Y.RPX_SITE_URL=`https://${$.host}`,Y}readLogTail($,w=40){try{return NM($.logPath,"utf8").split(`
|
|
235
|
-
`).slice(
|
|
236
|
-
`).trim()}catch{return""}}async stop(
|
|
229
|
+
`;if(J!==void 0)W+=`origin: ${J}\r
|
|
230
|
+
`;let Q=!1;for(let[B,j]of Y){let z=B.toLowerCase();if(ZH.has(z))continue;if(J!==void 0&&z==="origin")continue;if(z==="content-length")Q=!0;W+=`${B}: ${j}\r
|
|
231
|
+
`}if(W+=`connection: keep-alive\r
|
|
232
|
+
`,U&&!Q)W+=`content-length: ${U.length}\r
|
|
233
|
+
`;return W+=`\r
|
|
234
|
+
`,SH.encode(W)}async function iH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:W}=await $.read();if(U)break;if(W){if(A+=W.length,A>hG)return $.cancel().catch(()=>{}),null;Y.push(W)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var EH,cY,_8,TH,_W,n$,hG=1048576,LW=30000,CH=16384,DG=262144,yH=2097152,OH=524288,LH=8192,_H=4096,SH,xG,ZH,S8;var vG=t(()=>{({connect:EH}=Bun),cY=Symbol("rpx.pool.fallback"),_8=Symbol("rpx.pool.stale"),TH=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);_W=Symbol("rpx.pool.timeout"),n$=Symbol("rpx.pool.busy");SH=new TextEncoder,xG=new TextDecoder,ZH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);S8=new Map});function iG(w){let $=typeof w==="string"?{to:w}:w,Y=($.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:$.status??301,preservePath:$.preservePath??!0}}function mG(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as Gw from"node:path";function vY(w,$){if(typeof w==="string")return{dir:w,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:$};return{dir:w.dir,spa:w.spa??!1,pathRewriteStyle:w.pathRewriteStyle??"directory",maxAge:w.maxAge??0,cleanUrls:$}}function gH(w){let $=Gw.extname(w).toLowerCase();return mH[$]??"application/octet-stream"}function dH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=Gw.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function lH(w,$){let Y=dH(w);if(Y===null)return null;let A=Gw.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Gw.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:Gw.join($.dir,Y,"index.html")};if(A!=="")return{filePath:Gw.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:Gw.join($.dir,`${Y}.html`)};return{filePath:Gw.join($.dir,Y,"index.html")}}async function gG(w,$){let Y=lH(w,$);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=$.maxAge>0?`public, max-age=${$.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":gH(Y.filePath),"Cache-Control":A}});if($.spa){let J=Gw.join($.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var mH;var iY=t(()=>{mH={".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 nH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function rH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function nG(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function dG(w){if(w.upstreamPool)return LG(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function lG(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?nG(w,$.basePath):w,W=NW(U,$.pathRewrites);if(W)X=W.targetHost,U=W.targetPath,F("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function tH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function t1(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:W}=tH(X.url),Q=rH(X),B=w(Q,U);if(!B&&Y){let N=await Y(Q,U,X);if(N instanceof Response)return N;if(N&&N.retry)B=w(Q,U)}if(!B)return F("request",`No route found for host: ${Q}`,$),new Response(`No proxy configured for ${Q}`,{status:404});if(B.auth){let N=ZG(X,U,B.auth);if(N)return F("request",`401 challenge for ${Q}${U}`,$),N}if(B.redirect){let N=mG(B.redirect,U,W);return F("request",`${B.redirect.status} redirect ${Q}${U} → ${N}`,$),new Response(null,{status:B.redirect.status,headers:{location:N}})}if(B.static){let f=B.stripBasePathPrefix??!0?nG(U,B.basePath):U;return gG(f,B.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let N=dG(B);if(!J||!N)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:f,targetPath:R}=lG(U,B,N,$),y=`ws://${f}${R}${W}`,V={};for(let[O,S]of X.headers)if(!pH.has(O.toLowerCase())&&O.toLowerCase()!=="host")V[O]=S;V.host=f,V["x-forwarded-for"]="127.0.0.1",V["x-forwarded-proto"]="https",V["x-forwarded-host"]=Q;let T={targetUrl:y,forwardHeaders:V};if(J.upgrade(X,{data:T})){F("ws",`upgraded ${Q}${R} → ${y}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let j=dG(B);if(!j)return new Response(`No upstream configured for ${Q}`,{status:502});if(B.cleanUrls&&U.endsWith(".html")){let N=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:N}})}let{targetHost:z,targetPath:G}=lG(U,B,j,$),K=B.changeOrigin?`http://${z}`:void 0,E=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",q=B.upstreamPool;if(q)j.activeConnections++;try{let N=await uG({hostPort:z,method:X.method,path:`${G}${W}`,reqHeaders:X.headers,forwardedHost:Q,originOverride:K,body:X.body});if(q)L8(q,j);return N}catch(N){if(N===_W){if(F("request",`Upstream timeout for ${Q}`,$),q)PY(q,j);return new Response("Gateway Timeout",{status:504})}if(N===n$)return F("request",`Upstream pool saturated for ${Q}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(N===cY||!E)try{let f=new Headers(X.headers);if(f.set("host",z),f.set("x-forwarded-for","127.0.0.1"),f.set("x-forwarded-proto","https"),f.set("x-forwarded-host",Q),K!==void 0)f.set("origin",K);let R=await fetch(`http://${z}${G}${W}`,{method:X.method,headers:f,body:X.body,redirect:"manual"});if(q)L8(q,j);return R}catch(f){if(F("request",`Proxy error for ${Q}: ${f}`,$),q)PY(q,j);return new Response(`Proxy Error: ${f}`,{status:502})}if(F("request",`Proxy error for ${Q}: ${N}`,$),q)PY(q,j);return new Response(`Proxy Error: ${N}`,{status:502})}finally{if(q)j.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return F("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function a1(w){let $=new WeakMap,Y=nH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(Q){F("ws",`failed to open upstream ${X}: ${Q}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let W={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,W),U.addEventListener("open",()=>{W.upstreamOpen=!0;for(let Q of W.pending)U.send(Q);W.pending=[],W.pendingBytes=0}),U.addEventListener("message",(Q)=>{A.send(Q.data)}),U.addEventListener("close",(Q)=>{try{A.close(Q.code||1000,Q.reason||"")}catch{}}),U.addEventListener("error",()=>{F("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let W=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+W>Y){F("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=W},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var pH;var Z8=t(()=>{uY();vG();iY();X0();pH=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});import*as rG from"node:fs";import*as tG from"node:path";function mY(w,$){if(!w||!$.startsWith(pG))return null;let Y=$.slice(pG.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return rG.readFileSync(tG.join(w,Y),"utf8")}catch{return null}}var pG="/.well-known/acme-challenge/";var k8=()=>{};function _w(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function aH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function s1(w){let $=new Map;for(let A of w){let X=_w(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,W]of X)J.push({path:U,route:W});J.sort((U,W)=>W.path.length-U.path.length),Y.set(A,J)}return Y}function h8(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!F1(J))continue;if(TY($,J)){let W=J.length-1;if(W>X)X=W,A=U}}return A}function o1(w,$,Y){let A=h8(w,$);if(!A)return;for(let X of A)if(aH(Y,X.path))return X.route;return}var gY=()=>{};import*as dY from"node:fs/promises";import*as SW from"node:path";function sH(w){if(!w.endsWith(".crt"))return null;let $=w.slice(0,-4);if($.length===0)return null;if($.startsWith("_wildcard."))return`*.${$.slice(10)}`;return $}async function oH(w,$,Y,A){try{let[X,J]=await Promise.all([dY.readFile($,"utf8"),dY.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return F("sni",`skipping ${w}: ${X.message}`,A),null}}async function e1(w,$){let Y=new Map;if(w.certsDir){let X=[];try{X=await dY.readdir(w.certsDir)}catch(J){F("sni",`certsDir read failed (${w.certsDir}): ${J.message}`,$)}for(let J of X){let U=sH(J);if(!U)continue;let W=J.slice(0,-4);Y.set(U,{certPath:SW.join(w.certsDir,J),keyPath:SW.join(w.certsDir,`${W}.key`)})}}if(w.domains)for(let[X,J]of Object.entries(w.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await oH(X,J.certPath,J.keyPath,$);if(U)A.push(U)}return A}var D8=t(()=>{X0()});import*as _$ from"node:fs/promises";import*as ZW from"node:path";function wR(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function sG(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class p${config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??hX,this.issuer=w.issuer??WQ,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??eH;for(let $ of w.initial??[])this.certs.set($.serverName,$)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(w){return this.certs.has(w)}async isApproved(w){if(!sG(w))return!1;if(wR(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return F("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!sG(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return F("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return F("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{F("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose);let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),F("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),F("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=aG){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=aG){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([_$.readFile($,"utf8"),_$.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),F("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:ZW.join(this.certsDir,`${w}.crt`),keyPath:ZW.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await _$.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([_$.writeFile(A,$,"utf8"),_$.writeFile(X,Y,{encoding:"utf8",mode:384})])}}var eH=60000,aG=4096;var x8=t(()=>{iX();X0()});import{existsSync as $R,readdirSync as OL,readFileSync as YR,statSync as AR}from"node:fs";import{homedir as XR}from"node:os";import{isAbsolute as JR,join as wY}from"node:path";function oG(w,$){if(w==="~")return $;if(w.startsWith("~/"))return wY($,w.slice(2));return w}function BR(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function eG(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function jR(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function zR(w,$){let Y=$.readText(wY(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(wY(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function GR(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function KR(w,$){let Y=zR(w,$);if(Y?.command)return GR(Y);let A=$.fileExists(wY(w,"buddy")),X=$.readText(wY(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((Q)=>Q==="stacks"||Q.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function hW(w,$={}){let Y={dirExists:$.dirExists??kW.dirExists,fileExists:$.fileExists??kW.fileExists,readText:$.readText??kW.readText},A=$.detect??KR,X=$.homeDir??XR(),J=w.tlds??QR,U=(w.roots??UR).map((G)=>oG(G,X)),W=w.idleTimeoutMs??WR,Q=new Map;for(let G of w.sites??[])Q.set(G.to,G);let B=(G)=>G.idleTimeoutMs??W;function j(G){let K=nA(Q,G);if(!K)return null;let E=JR(K.dir)?K.dir:oG(K.dir,X),q=K.selfRegisters??!1,N=K.routes??[];if(!q&&N.length===0)N=A(E,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=w5({...K.env??{}},void 0,G);return{host:G,id:eG(G),dir:E,command:K.command,env:f,routes:N,selfRegisters:q,idleTimeoutMs:B(K),source:"config"}}function z(G){let K=jR(G,J);if(!K)return null;for(let E of U){let q=wY(E,K);if(!Y.dirExists(q))continue;let N=A(q,Y);if(!N)continue;let f=N.selfRegisters??!1;return{host:G,id:eG(G),dir:q,command:N.command,env:w5({...N.env??{}},N.urlEnv,G),routes:f?[]:N.routes??[],selfRegisters:f,idleTimeoutMs:W,source:"discovered"}}return null}return{resolve(G){let K=BR(G);if(!K)return null;return j(K)??z(K)}}}function w5(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var UR,QR,WR=1800000,kW;var DW=t(()=>{UR=["~/Code"],QR=["localhost","test"],kW={dirExists:(w)=>{try{return AR(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return $R(w)}catch{return!1}},readText:(w)=>{try{return YR(w,"utf8")}catch{return null}}}});import*as P8 from"node:net";function S$(w,$,Y){return F("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=P8.createServer(),J=setTimeout(()=>{F("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")F("port",`Port ${w} is in use`,Y),A(!0);else F("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),F("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),F("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function xW(w,$,Y,A=50){F("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await S$(X,$,Y))return F("port",`Found available port: ${X} after ${J} attempts`,Y),X;F("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function $5(w,$,Y=5000,A){return F("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=P8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{F("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{F("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{F("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class b8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await S$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await $5(w,this.hostname,3000,this.verbose))return F("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await xW(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await $5(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){F("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var hL;var PW=t(()=>{X0();hL=new b8});import*as u8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as FR}from"node:os";import*as bW from"node:path";import*as c8 from"node:process";function Zw(){return bW.join(FR(),".stacks","rpx","registry.d")}function lY(w){return typeof w==="string"&&w.length>0&&w.length<=128&&qR.test(w)}function uW(w,$){if(!lY($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return bW.join(w,`${$}.json`)}function b0(w){if(!Number.isInteger(w)||w<=0)return!1;try{return c8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function Y5(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&lY($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function NR(w){await p0.mkdir(w,{recursive:!0})}async function v8(w,$=Zw(),Y){if(!Y5(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await NR($);let A=uW($,w.id),X=`${A}.tmp.${c8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),F("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function nY(w,$=Zw(),Y){let A=uW($,w);try{await p0.unlink(A),F("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function ER(w,$=Zw(),Y){let A=uW($,w);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!Y5(J))return F("registry",`entry ${w} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return F("registry",`entry ${w} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function Sw(w=Zw(),$){let Y;try{Y=await p0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!lY(J))continue;let U=await ER(J,w,$);if(U)A.push(U)}return A}async function $Y(w=Zw(),$){let Y=await Sw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!b0(X.pid))F("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await nY(X.id,w,$).catch(()=>{}),A++}return A}function pY(w,$={}){let Y=$.dir??Zw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;u8.mkdirSync(Y,{recursive:!0});let U=null,W=!1,Q=null,B=!1,j=(N)=>{return JSON.stringify(N.map((f)=>({id:f.id,from:f.from,to:f.to,path:f.path,pid:f.pid,pathRewrites:f.pathRewrites,cleanUrls:f.cleanUrls,changeOrigin:f.changeOrigin,static:f.static,loadBalancer:f.loadBalancer})).sort((f,R)=>f.id.localeCompare(R.id)))},z=()=>{if(U=null,W)return;Sw(Y,J).then((N)=>{return Q=j(N),w(N)}).catch((N)=>{F("registry",`watcher onChange failed: ${N}`,J)})},G=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(z,A)},E=setInterval(()=>{if(W||B)return;B=!0,Sw(Y,J).then((N)=>{if(j(N)!==Q)G()}).catch((N)=>{F("registry",`watcher poll failed: ${N}`,J)}).finally(()=>{B=!1})},X),q=u8.watch(Y,{persistent:!0},(N,f)=>{if(f&&/\.tmp\.\d+\.\d+$/.test(f))return;G()});return q.on("error",(N)=>{F("registry",`watcher error: ${N}`,J)}),G(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(E),q.close()}}}var qR;var r$=t(()=>{X0();qR=/^[a-zA-Z0-9._-]+$/});import{closeSync as A5,openSync as TR,readFileSync as fR}from"node:fs";import*as X5 from"node:fs/promises";import{spawn as HR}from"node:child_process";import{homedir as RR}from"node:os";import*as rY from"node:path";import*as Vw from"node:process";class i8{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??Zw(),this.rpxDir=w.rpxDir??rY.join(RR(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??MR,this.pollIntervalMs=w.pollIntervalMs??IR,this.restartDelayMs=w.restartDelayMs??CR,this.killGraceMs=w.killGraceMs??yR,this.launch=w.launcher??LR(this.verbose),this.probePort=w.probePort??OR,this.pickPort=w.pickPort??((Y)=>xW(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??v8,this.removeEntry=w.removeEntry??nY;let $=w.reapIntervalMs??VR;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let W of w.routes){if($.has(W.portEnv))continue;let Q=await this.pickPort(W.defaultPort??3000);$.set(W.portEnv,Q)}let Y=rY.join(this.rpxDir,"sites",`${w.id}.log`);await X5.mkdir(rY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(W){J=`failed to spawn: ${W.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((W)=>this.onProcessExit(U,W)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((W)=>{F("sites",`readiness loop for ${w.host} threw: ${W}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await cW(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??_w(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((Q)=>_w(Q.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let Q of $.routes){if(Q===A)continue;let B=Y.get(Q.portEnv);if(B===void 0)continue;J.push({from:_w(Q.path),to:`localhost:${B}`,stripPrefix:Q.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let W=this.now()+2000;while(this.now()<W&&!this.isHostRoutable($.host))await cW(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Vw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return fR(w.logPath,"utf8").split(`
|
|
235
|
+
`).slice(-$).join(`
|
|
236
|
+
`).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),cW(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)F("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function cW(w){return new Promise(($)=>setTimeout($,w))}async function OR(w){let $=new AbortController,Y=setTimeout(()=>$.abort(),2000);try{return await fetch(`http://127.0.0.1:${w}/`,{signal:$.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function LR(w){let $=_R();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=TR(J,"a");try{let W=HR("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),Q=W.pid;if(Q===void 0)throw Error("spawn returned no pid");let B=new Promise((j)=>{W.once("exit",(z)=>{j(z)}),W.once("error",()=>{j(null)})}).finally(()=>{try{A5(U)}catch{}});return F("sites",`spawned pid ${Q}: sh -c ${Y} (cwd ${A})`,w),{pid:Q,exited:B,stop:(j="SIGTERM")=>{try{Vw.kill(-Q,j)}catch{try{W.kill(j)}catch{}}}}}catch(W){try{A5(U)}catch{}throw W}}}function _R(){if(Vw.platform==="win32")return null;if(!(typeof Vw.getuid==="function"&&Vw.getuid()===0))return null;let $=Number.parseInt(Vw.env.SUDO_UID??"",10),Y=Number.parseInt(Vw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var MR=120000,IR=200,VR=30000,CR=3000,yR=4000;var vW=t(()=>{gY();PW();r$();X0();lw()});function YY(w){return w.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function J5(w,$,Y){return`<!doctype html>
|
|
237
237
|
<html lang="en">
|
|
238
238
|
<head>
|
|
239
239
|
<meta charset="utf-8">
|
|
240
240
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
241
241
|
${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
|
|
242
|
-
<title>${
|
|
243
|
-
<style>${
|
|
242
|
+
<title>${YY(w)}</title>
|
|
243
|
+
<style>${SR}</style>
|
|
244
244
|
</head>
|
|
245
|
-
<body><main class="card">${
|
|
246
|
-
</html>`}function
|
|
247
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${
|
|
245
|
+
<body><main class="card">${$}</main></body>
|
|
246
|
+
</html>`}function iW(w){let $=Math.max(1,Math.round(w.sinceMs/1000)),Y=w.logTail?`<pre>${YY(w.logTail)}</pre>`:"",A=`
|
|
247
|
+
<div class="row"><div class="spinner"></div><h1>Starting ${YY(w.host)}…</h1></div>
|
|
248
248
|
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
249
249
|
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
250
|
-
<p>Booting for ${
|
|
251
|
-
${Y}`;return new Response(
|
|
252
|
-
<div class="row"><div class="dot"></div><h1>${
|
|
253
|
-
<p>${
|
|
254
|
-
${
|
|
255
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(
|
|
250
|
+
<p>Booting for ${$}s.</p>
|
|
251
|
+
${Y}`;return new Response(J5(`Starting ${w.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function mW(w){let $=w.logTail?`<pre>${YY(w.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
|
|
252
|
+
<div class="row"><div class="dot"></div><h1>${YY(w.host)} failed to start</h1></div>
|
|
253
|
+
<p>${YY(w.error)}</p>
|
|
254
|
+
${$}
|
|
255
|
+
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(J5(`${w.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var SR=`
|
|
256
256
|
:root { color-scheme: light dark }
|
|
257
257
|
* { box-sizing: border-box }
|
|
258
258
|
body {
|
|
@@ -278,63 +278,63 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
|
|
|
278
278
|
}
|
|
279
279
|
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
280
280
|
@keyframes spin { to { transform: rotate(360deg) } }
|
|
281
|
-
`;import{exec as
|
|
282
|
-
`),J=[],U=0;while(U<X.length){let
|
|
281
|
+
`;import{exec as ZR}from"node:child_process";import m8 from"node:fs";import kR from"node:os";import W5 from"node:path";import*as t$ from"node:process";import{promisify as hR}from"node:util";function U5(w){let $=w.trim().toLowerCase();return $==="localhost"||$.endsWith(".localhost")||$.endsWith(".localhost.")}async function B5(w){if(t$.platform==="win32")throw Error("Administrator privileges required on Windows");if(hY()){let{stdout:A}=await tY(w);return A}let $=I$(),Y=w.replace(/'/g,"'\\''");try{if($){let{stdout:A}=await tY(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`);return gW=!0,A}if(gW)try{let{stdout:A}=await tY(`sudo -n sh -c '${Y}'`);return A}catch(A){F("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await tY(`sudo -n sh -c '${Y}'`);return gW=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}function d8(w){let $=w.indexOf("#"),Y=($===-1?w:w.slice(0,$)).trim();if(!Y)return null;let A=$===-1?"":w.slice($+1).trim(),[X,...J]=Y.split(/\s+/);if(!X||J.length===0)return null;let U=/^rpx(?::pid=(\d+))?$/.exec(A);return{address:X,names:J,comment:A,rpxPid:U?.[1]?Number.parseInt(U[1],10):null,rpxManaged:U!==null}}function j5(w,$){let Y=d8(w);return Y!==null&&g8.has(Y.address)&&Y.names.includes($)}function xR(w,$){let Y=new Set($),A=new Set,X=w.split(`
|
|
282
|
+
`),J=[],U=0;while(U<X.length){let W=X[U];if(W.trim()===DR){let B=[],j=U+1;while(j<X.length){let G=X[j];if(G.trim()===""||G.trim().startsWith("#"))break;B.push(G),j++}let z=B.filter((G)=>{let K=d8(G),E=K!==null&&g8.has(K.address)&&K.names.some((q)=>Y.has(q));if(E){for(let q of K.names)if(Y.has(q))A.add(q)}return!E});if(z.length>0||B.length===0)J.push(W,...z);U=j;continue}let Q=d8(W);if(Q?.rpxManaged&&g8.has(Q.address)&&Q.names.some((B)=>Y.has(B))){for(let B of Q.names)if(Y.has(B))A.add(B);U++;continue}J.push(W),U++}while(J.length>0&&J[J.length-1].trim()==="")J.pop();return{content:`${J.join(`
|
|
283
283
|
`)}
|
|
284
|
-
`,removed:[...A]}}function
|
|
285
|
-
`)){let U=
|
|
284
|
+
`,removed:[...A]}}function PR(w,$){let Y=[],A=new Set,X=[];for(let J of w.split(`
|
|
285
|
+
`)){let U=d8(J);if(U?.rpxManaged&&U.rpxPid!==null&&g8.has(U.address)&&!$(U.rpxPid)){Y.push(...U.names),A.add(U.rpxPid);continue}X.push(J)}while(X.length>0&&X[X.length-1].trim()==="")X.pop();return{content:`${X.join(`
|
|
286
286
|
`)}
|
|
287
|
-
`,removed:Y,stalePids:[...A]}}async function
|
|
288
|
-
`),U=Y.filter((
|
|
289
|
-
127.0.0.1 ${
|
|
290
|
-
::1 ${
|
|
291
|
-
`);try{await
|
|
292
|
-
`);return
|
|
293
|
-
`,"utf8")}async function
|
|
287
|
+
`,removed:Y,stalePids:[...A]}}async function dW(w){try{return await m8.promises.readFile(W$,"utf-8")}catch{return F("hosts","Reading hosts file requires elevated permissions, using sudo",w),B5(`cat "${W$}"`)}}async function lW(w,$){let Y=W5.join(kR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await m8.promises.writeFile(Y,w,"utf8"),await B5(`cat "${Y}" | tee "${W$}" > /dev/null`)}finally{await m8.promises.unlink(Y).catch((A)=>{F("hosts",`Failed to remove temporary file: ${A}`,$)})}}async function aY(w,$){let Y=w.filter((X)=>!U5(X)),A=w.filter((X)=>U5(X));if(A.length>0)F("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,$);if(Y.length===0)return;F("hosts",`Adding hosts: ${Y.join(", ")}`,$),F("hosts",`Using hosts file at: ${W$}`,$);try{let X;try{X=await dW($)}catch(B){throw console.log(" Could not read hosts file — skipping hosts setup"),F("hosts",`sudo read also failed: ${B}`,$),Error(`Cannot read hosts file: ${B}`)}let J=X.split(`
|
|
288
|
+
`),U=Y.filter((B)=>!J.some((j)=>j5(j,B)));if(U.length===0){F("hosts","All hosts already exist in hosts file",$);return}let W=t$.pid,Q=U.map((B)=>`
|
|
289
|
+
127.0.0.1 ${B} ${Q5}:pid=${W}
|
|
290
|
+
::1 ${B} ${Q5}:pid=${W}`).join(`
|
|
291
|
+
`);try{await lW(X+Q,$),console.log(` Hosts updated: ${U.join(", ")}`)}catch(B){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((j)=>{console.log(` 127.0.0.1 ${j}`),console.log(` ::1 ${j}`)}),console.log(` Or run: sudo nano ${W$}`)}}catch(X){F("hosts",`Failed to manage hosts file: ${X.message}`,$)}}async function z5(w,$){F("hosts",`Removing hosts: ${w.join(", ")}`,$);try{let Y;try{Y=await dW($)}catch(J){throw F("hosts",`sudo read also failed: ${J}`,$),Error(`Cannot read hosts file: ${J}`)}let{content:A,removed:X}=xR(Y,w);if(X.length===0){F("hosts","No matching rpx-managed hosts found to remove",$);return}try{await lW(A,$),F("hosts",`Hosts removed successfully: ${X.join(", ")}`,$)}catch(J){F("hosts","Could not clean up hosts file automatically",$)}}catch(Y){F("hosts",`Failed to clean up hosts file: ${Y.message}`,$)}}async function sY(w,$){F("hosts",`Checking hosts: ${w}`,$);let Y;try{Y=await m8.promises.readFile(W$,"utf-8")}catch(X){F("hosts",`Error reading hosts file: ${X}`,$);try{let J=I$(),U;if(J)U=`echo '${J}' | sudo -S cat "${W$}" 2>/dev/null`;else U=`sudo -n cat "${W$}" 2>/dev/null || cat "${W$}" 2>/dev/null || echo ""`;let{stdout:W}=await tY(U);Y=W}catch(J){return F("hosts",`Cannot read hosts file, assuming entries don't exist: ${J}`,$),w.map(()=>!1)}}let A=Y.split(`
|
|
292
|
+
`);return w.map((X)=>A.some((J)=>j5(J,X)))}async function AY(w={}){let $=w.isAlive??b0,Y;try{Y=await dW(w.verbose)}catch(U){return F("hosts",`stale hosts GC: cannot read hosts file: ${U}`,w.verbose),[]}let{content:A,removed:X,stalePids:J}=PR(Y,$);if(X.length===0)return[];try{return await lW(A,w.verbose),F("hosts",`stale hosts GC: removed ${X.join(", ")} (dead pid(s): ${J.join(", ")})`,w.verbose),[...new Set(X)]}catch(U){return F("hosts",`stale hosts GC: write failed: ${U}`,w.verbose),[]}}var tY,W$,Q5="# rpx",DR="# Added by rpx",g8,gW=!1;var l8=t(()=>{r$();X0();tY=hR(ZR);W$=t$.platform==="win32"?W5.join(t$.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",g8=new Set(["127.0.0.1","::1"])});import{spawn as bR}from"node:child_process";import*as B$ from"node:fs/promises";import{homedir as uR}from"node:os";import*as oY from"node:path";import*as y0 from"node:process";function j$(){return oY.join(uR(),".stacks","rpx")}function K5(w=j$()){return oY.join(w,"daemon.pid")}async function G5(w=j$()){try{let $=await B$.readFile(K5(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function cR(w=j$()){await B$.unlink(K5(w)).catch(()=>{})}function vR(){let w=y0.execPath,$=oY.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&y0.argv[1])return[w,y0.argv[1],"daemon:start"];return[w,"daemon:start"]}async function F5(w={}){let $=w.rpxDir??j$(),Y=w.verbose??!1;await z$({rpxDir:$,verbose:Y}).catch((j)=>{F("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await G5($);if(A!==null&&b0(A))return F("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)F("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await cR($);await B$.mkdir($,{recursive:!0});let X=w.spawnCommand??vR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");F("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=bR(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??y0.cwd(),env:w.spawnEnv?{...y0.env,...w.spawnEnv}:y0.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=w.startupTimeoutMs??5000,Q=w.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await G5($);if(j!==null&&b0(j))return F("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,Q))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${$})`)}var nW=t(()=>{lw();O8();Z8();k8();gY();D8();x8();DW();vW();iY();uY();r$();l8();XY();X0()});import*as k$ from"node:fs/promises";import{homedir as iR}from"node:os";import*as pW from"node:path";function N5(){return pW.join(iR(),".stacks","rpx")}function rW(w=N5()){return pW.join(w,mR)}async function p8(w=N5()){try{let $=await k$.readFile(rW(w),"utf8"),Y=JSON.parse($);if(Y.version!==n8||!Array.isArray(Y.resolvers))return null;return{version:n8,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch($){if($.code==="ENOENT")return null;throw $}}async function E5(w,$){await k$.mkdir(w,{recursive:!0}),await k$.writeFile(rW(w),`${JSON.stringify($,null,2)}
|
|
293
|
+
`,"utf8")}async function tW(w){await k$.rm(rW(w),{force:!0})}function T5(w){let $=w.trim().toLowerCase().replace(/\.$/,"");if(!$||$.includes("127.0.0.1"))return null;if($==="localhost"||$.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return null;if(!/^[a-z0-9.-]+$/.test($))return null;return $}function gR(w){let $=T5(w);if(!$)return null;let Y=$.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function aW(w){let $=new Set;for(let Y of w){let A=gR(Y);if(A)$.add(A)}return Array.from($).sort()}function sW(w){let $=new Set;for(let Y of w){let A=T5(Y);if(A)$.add(A)}return Array.from($).sort()}var n8=1,mR="dns-state.json",q5;var f5=t(()=>{q5=["com","test","dev","app","page","local","localhost","example","invalid"]});var t8={};EB(t8,{tearDownDevelopmentDns:()=>Z$,syncDevelopmentDnsFromRegistry:()=>a$,stopDnsServer:()=>oW,startDnsServer:()=>O5,setupResolver:()=>eR,setupDevelopmentDns:()=>YB,resolverFilePath:()=>JY,removeResolver:()=>$M,removeLegacyTldResolvers:()=>$B,reconcileStaleDevelopmentDns:()=>z$,isRpxDevelopmentDnsAnswering:()=>L5,isDnsServerRunning:()=>pR,contentLooksLikeRpxResolver:()=>_5,RPX_RESOLVER_MARKER:()=>I5,DNS_PORT:()=>wA});import H5 from"node:dgram";import*as R5 from"node:fs/promises";import*as M5 from"node:path";import*as G$ from"node:process";function C5(w){return{id:w.readUInt16BE(0),flags:w.readUInt16BE(2),qdcount:w.readUInt16BE(4),ancount:w.readUInt16BE(6),nscount:w.readUInt16BE(8),arcount:w.readUInt16BE(10)}}function y5(w,$,Y=0){let A=[],X=$,J=0;while(!0){if(X>=w.length||++J>128)break;let U=w[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=w.length||Y>=10)break;let W=w.readUInt16BE(X)&16383,{name:Q}=y5(w,W,Y+1);if(Q)A.push(Q);X+=2;break}if(X++,X+U>w.length)break;A.push(w.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function dR(w,$){let{name:Y,newOffset:A}=y5(w,$),X=w.readUInt16BE(A),J=w.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function eY(w){let $=w.split("."),Y=[];for(let A of $)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function lR(w,$,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE(w,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),A.push(X),A.push(eY($.name));let J=Buffer.alloc(4);J.writeUInt16BE($.type,0),J.writeUInt16BE($.class,2),A.push(J),A.push(eY($.name));let U=Buffer.alloc(10);if(U.writeUInt16BE($.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),$.type===1){U.writeUInt16BE(4,8),A.push(U);let W=Y.split(".").map((Q)=>Number.parseInt(Q,10));A.push(Buffer.from(W))}else if($.type===28)U.writeUInt16BE(16,8),A.push(U),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return X.writeUInt16BE(33155,2),X.writeUInt16BE(0,6),Buffer.concat([X,eY($.name),J]);return Buffer.concat(A)}function nR(w,$){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE(w,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(eY($.name));let X=Buffer.alloc(4);return X.writeUInt16BE($.type,0),X.writeUInt16BE($.class,2),Y.push(X),Buffer.concat(Y)}async function O5(w,$){if(G$.platform!=="darwin")return!1;let Y=sW(w);if(Y.length===0)return!1;if(t0){for(let A of Y)r8.add(A);return F("dns","DNS server already running — merged domains",$),!0}return r8=new Set(Y),new Promise((A)=>{t0=H5.createSocket("udp4"),t0.on("error",(X)=>{F("dns",`DNS server error: ${X.message}`,$),t0?.close(),t0=null,A(!1)}),t0.on("message",(X,J)=>{try{let U=C5(X),{question:W}=dR(X,12);F("dns",`Query for ${W.name} type ${W.type} from ${J.address}`,$);let Q=W.name.toLowerCase(),B=!1;for(let z of r8)if(Q===z||Q.endsWith(`.${z}`)){B=!0;break}let j;if(B&&(W.type===1||W.type===28))j=lR(U.id,W,"127.0.0.1"),F("dns",`Responding with localhost for ${W.name}`,$);else j=nR(U.id,W),F("dns",`NXDOMAIN for ${W.name}`,$);t0?.send(j,J.port,J.address)}catch(U){F("dns",`Error processing DNS query: ${U}`,$)}}),t0.on("listening",()=>{let X=t0?.address();F("dns",`DNS server listening on ${X?.address}:${X?.port}`,$),A(!0)});try{t0.bind(wA,"127.0.0.1")}catch(X){F("dns",`Failed to bind DNS server: ${X}`,$),A(!1)}})}function oW(w){if(t0)F("dns","Stopping DNS server",w),t0.close(),t0=null,r8=new Set}function pR(){return t0!==null}async function L5(w,$=500){let Y=w.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=H5.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},$);X.on("message",(W)=>{clearTimeout(J),X.close();try{let Q=C5(W);A(Q.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=rR(Y,1);X.send(U,wA,"127.0.0.1",(W)=>{if(W)clearTimeout(J),X.close(),A(!1)})})}function rR(w,$){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([eY(w),Buffer.from([0,$,0,1])]);return Buffer.concat([Y,A])}function tR(){return`${I5}
|
|
294
294
|
nameserver 127.0.0.1
|
|
295
|
-
port ${
|
|
296
|
-
`}function
|
|
295
|
+
port ${wA}
|
|
296
|
+
`}function JY(w){return M5.join(V5,w)}function _5(w){return w.includes("127.0.0.1")&&w.includes(String(wA))}async function aR(w){try{return await R5.readFile(JY(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function eW(w){if(G$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),g1));if(!A()&&!Y()){F("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),F("dns","DNS cache flushed",w)}catch(X){F("dns",`Could not flush DNS cache: ${X}`,w)}}function S5(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function sR(w,$){S5(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),g1)),A=tR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${V5} && printf "%b" "${A}" > ${JY(w)}'`;Y(X),F("dns",`Created ${JY(w)}`,$)}async function oR(w,$){S5(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),g1));Y(`rm -f ${JY(w)}`),F("dns",`Removed ${JY(w)}`,$)}async function eR(w,$){return YB({domains:$??[],verbose:w})}async function wM(w,$){if(G$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),g1));if(!A()&&!Y())return F("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await sR(X,$);return await eW($),!0}catch(X){return F("dns",`Failed to create resolver file: ${X}`,$),!1}}async function wB(w,$){if(G$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),g1));if(!A()&&!Y())return;try{for(let X of w)await oR(X,$);await eW($)}catch(X){F("dns",`Failed to remove resolver files: ${X}`,$)}}async function $B(w){if(G$.platform!=="darwin")return[];let $=[];for(let Y of q5){let A=await aR(Y);if(A&&_5(A))await wB([Y],w),$.push(Y)}return $}async function YB(w){let $=w.rpxDir??j$(),Y=sW(w.domains);if(Y.length===0)return!1;let A=aW(Y),X=await O5(Y,w.verbose);if(!X){let W=Y[0];if(W&&await L5(W))X=!0;else F("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await wM(A,w.verbose))return!1;let U={version:n8,resolvers:A,domains:Y,ownerPid:w.ownerPid??G$.pid,updatedAt:new Date().toISOString()};return await E5($,U),!0}async function a$(w,$={}){let Y=w.map((Q)=>Q.to).filter(Boolean),A=$.rpxDir??j$(),X=aW(Y),W=((await p8(A))?.resolvers??[]).filter((Q)=>!X.includes(Q));if(W.length>0)await wB(W,$.verbose);if(X.length===0){oW($.verbose),await tW(A);return}await YB({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??G$.pid})}async function Z$(w={}){let $=w.rpxDir??j$();oW(w.verbose);let A=(await p8($))?.resolvers??[];await wB(A,w.verbose),await $B(w.verbose),await tW($)}async function $M(w){await Z$({verbose:w})}async function z$(w={}){let $=w.rpxDir??j$(),Y=await p8($),A=Y?.ownerPid!=null&&b0(Y.ownerPid);if(Y&&!A){F("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await Z$(w);return}let X=await $B(w.verbose);if(X.length>0)F("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await eW(w.verbose)}var wA=15353,I5="# managed-by: rpx",V5="/etc/resolver",t0=null,r8;var XY=t(()=>{nW();f5();r$();X0();r8=new Set});import{dirname as LM,join as _M}from"path";import*as P0 from"process";import{fileURLToPath as SM}from"url";import{existsSync as q6}from"node:fs";import qJ from"node:fs/promises";import TB from"node:os";import NJ from"node:path";import P$ from"node:process";import{EventEmitter as N6}from"node:events";import K$ from"node:process";import fB from"node:process";import HJ from"node:process";import JA from"node:process";import GY from"node:process";import MB from"node:tty";import AK,{stdin as aM,stdout as sM}from"node:process";import VB,{stdin as UK,stdout as QK}from"node:process";import WK from"node:readline";class yB{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=TB.homedir(),$=NJ.join(w,".config","clapp");this.configPath=NJ.join($,"telemetry.json")}async isEnabled(){if(P$.env.DO_NOT_TRACK==="1"||P$.env.DO_NOT_TRACK==="true")return!1;if(P$.env.NO_TELEMETRY==="1"||P$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:TB.platform(),nodeVersion:P$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:P$.env.DO_NOT_TRACK==="1"||P$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(q6(this.configPath)){let w=await qJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse(w),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(w){this.config=w;try{let $=NJ.dirname(this.configPath);await qJ.mkdir($,{recursive:!0}),await qJ.writeFile(this.configPath,JSON.stringify(w,null,2),"utf-8")}catch{}}generateUserId(){let w=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${w}-${$}`}}var uM=new yB;function E6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let W of Object.keys(A))for(let Q of A[W])J[Q]=W;for(let W of X)if(A[W])for(let Q of A[W])X.add(Q);function U(W,Q){let B=J[W]||W;if(Y[B]=Q,A[B])for(let j of A[B])Y[j]=Q;if(J[W]&&A[J[W]])for(let j of A[J[W]])Y[j]=Q;Y[W]=Q}for(let W=0;W<w.length;W++){let Q=w[W];if(Q==="--"){Y._.push(...w.slice(W+1));break}if(Q.startsWith("--")){let B=Q.indexOf("=");if(B!==-1){let j=Q.slice(2,B),z=Q.slice(B+1);U(j,z)}else{let j=Q.slice(2);if(j.startsWith("no-")){let G=j.slice(3);U(G,!1);continue}let z=J[j]||j;if(X.has(z)||X.has(j))U(j,!0);else{let G=w[W+1];if(G!==void 0&&!G.startsWith("-"))U(j,G),W++;else U(j,!0)}}}else if(Q.startsWith("-")&&Q.length>1){let B=Q.slice(1);for(let j=0;j<B.length;j++){let z=B[j],G=J[z]||z;if(j===B.length-1&&!X.has(G)&&!X.has(z)){let K=w[W+1];if(K!==void 0&&!K.startsWith("-"))U(z,K),W++;else U(z,!0)}else U(z,!0)}}else Y._.push(Q)}return Y}function fJ(w){return w.replace(/[<[].+/,"").trim()}function T6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(W)=>{let Q=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),Q=!0;return{required:W[0].startsWith("<"),value:B,variadic:Q}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function f6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((W)=>A.names.includes(W))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function HB(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function EJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function H6(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function R6(w,$,Y){let A=0,X=$.length,J=w,U;for(;A<X;++A)U=J[$[A]],J=J[$[A]]=A===X-1?Y:U!=null?U:!!~$[A+1].indexOf(".")||!(+$[A+1]>-1)?{}:[]}function M6(w,$){for(let Y of Object.keys($)){let A=$[Y];if(A.shouldTransform){if(w[Y]=Array.prototype.concat.call([],w[Y]),typeof A.transformFunction==="function")w[Y]=w[Y].map(A.transformFunction)}}}function I6(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function OB(w){return w.split(".").map(($,Y)=>{return Y===0?H6($):$}).join(".")}class XA extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
|
|
297
297
|
|
|
298
298
|
Stack trace:
|
|
299
|
-
${this.stack}`;return this.message}}function
|
|
300
|
-
`);let
|
|
299
|
+
${this.stack}`;return this.message}}function V6(){let{env:w}=fB,{TERM:$,TERM_PROGRAM:Y}=w;if(fB.platform!=="win32")return $!=="linux";return Boolean(w.WT_SESSION)||Boolean(w.TERMINUS_SUBLIME)||w.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||w.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var WA="\x1B",j0=`${WA}[`;var uw={to(w,$){if(!$)return`${j0}${w+1}G`;return`${j0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${j0}${-w}D`;else if(w>0)Y+=`${j0}${w}C`;if($<0)Y+=`${j0}${-$}A`;else if($>0)Y+=`${j0}${$}B`;return Y},up:(w=1)=>`${j0}${w}A`,down:(w=1)=>`${j0}${w}B`,forward:(w=1)=>`${j0}${w}C`,backward:(w=1)=>`${j0}${w}D`,nextLine:(w=1)=>`${j0}E`.repeat(w),prevLine:(w=1)=>`${j0}F`.repeat(w),left:`${j0}G`,hide:`${j0}?25l`,show:`${j0}?25h`,save:`${WA}7`,restore:`${WA}8`};var TJ={screen:`${j0}2J`,up:(w=1)=>`${j0}1J`.repeat(w),down:(w=1)=>`${j0}J`.repeat(w),line:`${j0}2K`,lineEnd:`${j0}K`,lineStart:`${j0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?uw.up():"");if(w)$+=uw.left;return $}},mM={screen:`${WA}c`};function C6(w,$){let Y=[];for(let A=0;A<=$.length;A++)Y[A]=[A];for(let A=0;A<=w.length;A++)Y[0][A]=A;for(let A=1;A<=$.length;A++)for(let X=1;X<=w.length;X++)if($.charAt(A-1)===w.charAt(X-1))Y[A][X]=Y[A-1][X-1];else Y[A][X]=Math.min(Y[A-1][X-1]+1,Y[A][X-1]+1,Y[A-1][X]+1);return Y[$.length][w.length]}function LB(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:C6(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class _B{rawName;description;name;names;isBoolean;required;config;negated;constructor(w,$,Y){if(this.rawName=w,this.description=$,this.config=Object.assign({},Y),w=w.replace(/\.\*/g,""),this.negated=!1,this.names=fJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return OB(X)}).sort((A,X)=>A.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(w.includes("<"))this.required=!0;else if(w.includes("["))this.required=!1;else this.isBoolean=!0}}var dM=HJ.argv,y6=`${HJ.platform}-${HJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,RB=JA.argv,O6=`${JA.platform}-${JA.arch} node-${JA.version}`;class RJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(w,$,Y,A){this.rawName=w,this.description=$,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=fJ(w);let X=fJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=T6(w),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage(w){return this.usageText=w,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(w,$="-v, --version"){return this.versionNumber=w,this.option($,"Display version number"),this}example(w){return this.examples.push(w),this}option(w,$,Y){let A=new _B(w,$,Y);return this.options.push(A),this}alias(w){return this.aliasNames.push(w),this}action(w){return this.commandAction=w,this}before(w){return this.beforeHooks.push(w),this}after(w){return this.afterHooks.push(w),this}use(w){return this.middleware.push(w),this}isMatched(w){if(this.aliasNames.includes(w))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===w;return this.name===w}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof MJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let Q=HB($.map((K)=>K.rawName)),B=new Map,j=[];for(let K of $)if(K.namespace){if(!B.has(K.namespace))B.set(K.namespace,[]);B.get(K.namespace).push(K)}else j.push(K);let z="";if(j.length>0)z+=j.map((K)=>{return` ${EJ(K.rawName,Q.length)} ${K.description}`}).join(`
|
|
300
|
+
`);let G=Array.from(B.keys()).sort();for(let K of G){let E=B.get(K);if(z.length>0)z+=`
|
|
301
301
|
|
|
302
|
-
`;
|
|
303
|
-
`,
|
|
304
|
-
`)}J.push({title:"Commands",body:
|
|
305
|
-
`)})}let
|
|
306
|
-
`)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((
|
|
307
|
-
`)});if(X)J=X(J)||J;console.log(J.map((
|
|
308
|
-
${
|
|
302
|
+
`;z+=` ${K}:
|
|
303
|
+
`,z+=E.map((q)=>{return` ${EJ(q.rawName,Q.length-2)} ${q.description}`}).join(`
|
|
304
|
+
`)}J.push({title:"Commands",body:z}),J.push({title:"For more info, run any command with the `--help` flag",body:$.map((K)=>` $ ${w}${K.displayName===""?"":` ${K.displayName}`} --help`).join(`
|
|
305
|
+
`)})}let W=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((Q)=>Q.name!=="version");if(W.length>0){let Q=HB(W.map((B)=>B.rawName));J.push({title:"Options",body:W.map((B)=>{return` ${EJ(B.rawName,Q.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
|
|
306
|
+
`)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((Q)=>{if(typeof Q==="function")return Q(w);return Q}).join(`
|
|
307
|
+
`)});if(X)J=X(J)||J;console.log(J.map((Q)=>{return Q.title?`${Q.title}:
|
|
308
|
+
${Q.body}`:Q.body}).join(`
|
|
309
309
|
|
|
310
|
-
`))}outputVersion(){let{name
|
|
310
|
+
`))}outputVersion(){let{name:w}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${w}/${$} ${typeof Bun<"u"?y6:O6}`)}checkRequiredArgs(){let w=this.args.filter(($)=>$.required).length;if(this.cli.args.length<w){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new XA(`Missing required argument${Y.length>1?"s":""}: ${A}
|
|
311
311
|
|
|
312
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options
|
|
312
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:w,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys(w))if(Y!=="--"&&!this.hasOption(Y)&&!$.hasOption(Y)){let X=[...$.options,...this.options].flatMap((Q)=>Q.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=LB(Y,X),W=`Unknown option \`${J}\``;if(U.length>0)W+=`
|
|
313
313
|
|
|
314
|
-
Did you mean one of these?`,U.forEach((
|
|
315
|
-
• ${
|
|
314
|
+
Did you mean one of these?`,U.forEach((Q)=>{let B=Q.length>1?`--${Q}`:`-${Q}`;W+=`
|
|
315
|
+
• ${B}`});throw W+=`
|
|
316
316
|
|
|
317
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
317
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new XA(W)}}}checkOptionValue(){let{options:w,globalCommand:$}=this.cli,Y=[...$.options,...this.options];for(let A of Y){let X=w[A.name.split(".")[0]];if(A.required){let J=Y.some((U)=>U.negated&&U.names.includes(A.name));if(X===!0||X===!1&&!J)throw new XA(`Option \`${A.rawName}\` requires a value.
|
|
318
318
|
|
|
319
|
-
Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class
|
|
319
|
+
Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class MJ extends RJ{constructor(w){super("@@global@@","",{},w)}}var L6=RJ,F$={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 jY={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function _6(){return!0}function S6(){let w={};w.supportsColor=_6();function $(A,X=[]){let J=A===""?[]:[...X,A],U=function(Q){if(!w.supportsColor)return Q;let B="",j="";for(let z of J)if(z in jY&&jY[z]in F$){let G=jY[z];B+=F$[G][0],j=F$[G][1]+j}else if(z in F$)B+=F$[z][0],j=F$[z][1]+j;return B+Q+j},W=[...Object.keys(F$),...Object.keys(jY)];for(let Q of W)if(!(Q in U))Object.defineProperty(U,Q,{get(){return $(Q,J)}});return U}let Y=[...Object.keys(F$),...Object.keys(jY)];for(let A of Y)if(!(A in w))Object.defineProperty(w,A,{get(){return $(A)}});return w}var zY=S6();class IJ extends N6{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(w=""){super();this.name=w,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new MJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(w){if(this.signalHandlersSet)return this;let $=async(Y)=>{if(console.log(`
|
|
320
320
|
|
|
321
|
-
Received ${Y}, cleaning up...`)
|
|
322
|
-
✗ Command "${
|
|
323
|
-
`)),this.enableDidYouMean){let
|
|
324
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
325
|
-
`),
|
|
326
|
-
`),A
|
|
327
|
-
`),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var
|
|
328
|
-
`),U=[];for(let
|
|
329
|
-
`)}class
|
|
330
|
-
`)
|
|
331
|
-
`).length-1;this.output.write(
|
|
332
|
-
`);this.output.write(A[Y]),this._prevFrame
|
|
321
|
+
Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error during cleanup:",A)}K$.exit(0)};return K$.on("SIGINT",()=>$("SIGINT")),K$.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(w=!0){return this.enableDidYouMean=w,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(w){return this.globalCommand.usage(w),this}command(w,$,Y){if(!Y)Y={};let A=new L6(w,$||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(w,$,Y){return this.globalCommand.option(w,$,Y),this}help(w){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=w,this.showHelpOnExit=!0,this}version(w,$="-v, --version"){return this.globalCommand.version(w,$),this.showVersionOnExit=!0,this}example(w){return this.globalCommand.example(w),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:w,options:$},Y,A){if(this.args=w,this.options=$,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(w){if(console.log(zY.red(`
|
|
322
|
+
✗ Command "${w}" not found.
|
|
323
|
+
`)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=LB(w,$);if(Y.length>0)console.log(zY.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${zY.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(zY.dim("Run"),`${this.name} --help`,zY.dim("to see all available commands")),K$.exit(1)}async parse(w=RB,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(Q){throw this.handleUsageError(Q),Q}if(this.rawArgs=w,!this.name)this.name=w[1]?I6(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let Q of this.commands)if(Q.isMatched(U)){let B=this.mri(J,Q);X=!1;let j={...B,args:B.args.slice(1)};this.setParsedInfo(j,Q,U),this.emit(`command:${U}`,Q);break}}if(X){for(let Q of this.commands)if(Q.name===""){X=!1;let B=this.mri(J,Q);this.setParsedInfo(B,Q),this.emit("command:!",Q);break}}if(X){let Q=this.mri(w.slice(2));this.setParsedInfo(Q)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return W}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=f6(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=E6(w,A),W={_:U._};for(let G of Object.keys(U))if(G!=="_")W[OB(G)]=U[G];let Q=W._,B={"--":X},j=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let G of Y){if(!j&&G.config.default!==void 0)for(let K of G.names)B[K]=G.config.default;if(Array.isArray(G.config.type)){if(z[G.name]===void 0)z[G.name]={shouldTransform:!0,transformFunction:G.config.type[0]}}}for(let G of Object.keys(W))if(G!=="_"){let K=G.split(".");R6(B,K,W[G]),M6(B,z)}return{args:Q,options:B}}async run(w=RB){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
|
|
324
|
+
Run \`${this.name??"cli"} --help\` for usage.`;K$.stderr.write(`${J}${X}${U}
|
|
325
|
+
`),K$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((W,Q)=>{if(W.variadic)A.push(w.slice(Q));else A.push(w[Q])}),A.push($);let X={command:Y,args:A,options:$};for(let W of Y.beforeHooks)await W(X);let J,U=async()=>{let W=Y.commandAction.apply(this,A);if(W instanceof Promise)J=await W;else J=W;return J};if(Y.middleware.length>0){let W=0,Q=async()=>{if(W<Y.middleware.length){let B=Y.middleware[W++];await B({...X,next:Q})}else await U()};await Q()}else await U();for(let W of Y.afterHooks)await W(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return K$.removeAllListeners("SIGINT"),K$.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 SB{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(w){if(!this.enabled){this.misses++;return}let $=this.cache.get(w);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(w),this.misses++;return}return this.hits++,$.value}set(w,$,Y=5000){if(!this.enabled)return;this.cache.set(w,{value:$,timestamp:Date.now(),ttl:Y})}has(w){if(!this.enabled)return!1;let $=this.cache.get(w);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(w),!1;return!0}delete(w){this.cache.delete(w)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let w=Date.now();for(let[$,Y]of this.cache.entries())if(w-Y.timestamp>Y.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var nM=new SB;function Z6(){if("FORCE_COLOR"in GY.env)return GY.env.FORCE_COLOR!=="0";if("NO_COLOR"in GY.env||GY.env.TERM==="dumb")return!1;if(GY.platform==="win32")return!0;return MB.isatty(1)&&MB.isatty(2)}var ZB=Z6();function A0(w,$){if(!ZB)return(Y)=>Y;return(Y)=>w+Y+$}var k6=A0("\x1B[0m","\x1B[0m"),h6=A0("\x1B[31m","\x1B[39m"),D6=A0("\x1B[32m","\x1B[39m"),x6=A0("\x1B[33m","\x1B[39m"),P6=A0("\x1B[34m","\x1B[39m"),b6=A0("\x1B[35m","\x1B[39m"),u6=A0("\x1B[36m","\x1B[39m"),c6=A0("\x1B[37m","\x1B[39m"),v6=A0("\x1B[90m","\x1B[39m"),i6=A0("\x1B[1m","\x1B[22m"),m6=A0("\x1B[3m","\x1B[23m"),g6=A0("\x1B[4m","\x1B[24m"),d6=A0("\x1B[2m","\x1B[22m"),l6=A0("\x1B[7m","\x1B[27m"),n6=A0("\x1B[8m","\x1B[28m"),p6=A0("\x1B[9m","\x1B[29m"),r6=A0("\x1B[41m","\x1B[49m"),t6=A0("\x1B[42m","\x1B[49m"),a6=A0("\x1B[43m","\x1B[49m"),s6=A0("\x1B[44m","\x1B[49m"),o6=A0("\x1B[45m","\x1B[49m"),e6=A0("\x1B[46m","\x1B[49m"),wK=A0("\x1B[47m","\x1B[49m"),$K=ZB,YK={reset:k6,red:h6,green:D6,yellow:x6,blue:P6,magenta:b6,cyan:u6,white:c6,gray:v6,bold:i6,italic:m6,underline:g6,dim:d6,inverse:l6,hidden:n6,strikethrough:p6,bgRed:r6,bgGreen:t6,bgYellow:a6,bgBlue:s6,bgMagenta:o6,bgCyan:e6,bgWhite:wK,isColorSupported:$K},UA=YK,XK=["up","down","left","right","space","enter","cancel"],QA={actions:new Set(XK),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function kB(w,$){if(typeof w==="string")return QA.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(kB(Y,$))return!0}return!1}function JK(w,$){if(w===$)return[];let Y=w.split(`
|
|
326
|
+
`),A=$.split(`
|
|
327
|
+
`),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var oM=AK.platform.startsWith("win"),IB=Symbol("clapp:cancel");function AA(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function BK(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function jK(w){return BK(w).length}function CB(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
|
|
328
|
+
`),U=[];for(let W of J){if(jK(W)<=$){U.push(X?W.trimEnd():W);continue}if(A){let Q="",B=0,j=0;while(j<W.length){let z=W.slice(j).match(/^\x1b\[[0-9;]*m/);if(z){Q+=z[0],j+=z[0].length;continue}if(B>=$)U.push(X?Q.trimEnd():Q),Q="",B=0;Q+=W[j],B++,j++}if(Q)U.push(X?Q.trimEnd():Q)}else U.push(X?W.trimEnd():W)}return U.join(`
|
|
329
|
+
`)}class VJ{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=UK,output:A=QK,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w(IB);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=WK.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),AA(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(uw.show),this.output.off("resize",this.render),AA(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(uw.show),this.output.off("resize",this.render),AA(this.input,!1),w(IB)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&QA.aliases.has($.name))this.emit("cursor",QA.aliases.get($.name));if(QA.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(kB([w,$?.name,$?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
330
|
+
`),AA(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let w=CB(this._prevFrame,VB.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
331
|
+
`).length-1;this.output.write(uw.move(-999,w*-1))}render(){let w=CB(this._render(this)??"",VB.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(uw.hide);else{let $=JK(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(uw.move(0,Y)),this.output.write(TJ.lines(1));let A=w.split(`
|
|
332
|
+
`);this.output.write(A[Y]),this._prevFrame=w,this.output.write(uw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(uw.move(0,Y)),this.output.write(TJ.down());let X=w.split(`
|
|
333
333
|
`).slice(Y);this.output.write(X.join(`
|
|
334
|
-
`)),this._prevFrame
|
|
335
|
-
`)}finally{await A.close()}return
|
|
336
|
-
`),
|
|
337
|
-
`):K.ca}:null,T=!1,q=[];function E(h){for(let hw of q)try{hw.kill(h)}catch{}}async function H(h){await S6(Y,h,F),E("SIGHUP")}let M=$.onDemandTls,y=M?.enabled?new mY({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??O$.join(Y,"on-demand-certs"),initial:G,verbose:B,onCertAdded:(h)=>{H(h)}}):null;await S6(Y,y?y.sniEntries():G,F);let C=await Q$(A,B);await Uw({rpxDir:Y,verbose:B}).catch((h)=>{N("daemon",`DNS reconcile on start failed: ${h}`,B)}),await pw(C,{rpxDir:Y,verbose:B,ownerPid:Q.pid}).catch((h)=>{N("daemon",`DNS setup on start failed: ${h}`,B)}),await $Y(A,B).catch(()=>{}),await YY({verbose:B}).catch(()=>{});let f=lY((h)=>{pw(h,{rpxDir:Y,verbose:B,ownerPid:Q.pid}).catch((hw)=>{N("daemon",`DNS sync on registry change failed: ${hw}`,B)})},{dir:A,verbose:B}),I=setInterval(()=>{$Y(A,B).catch(()=>{}),YY({verbose:B}).catch(()=>{})},W);I.unref?.();let L=null;if(J>0)L=Bun.serve({port:J,hostname:U,fetch(h){return P6(h,y,$.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let Z=10,P0=60000,S$=30000,Z$=0,tw=Date.now();function Bw(){if(T)return;let h={...Q.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:B?"1":"0"},hw=Bun.spawn(Y4(),{env:h,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(WJ,sw){if(T)return;let M$=q.indexOf(WJ);if(M$!==-1)q.splice(M$,1);let WY=Date.now();if(WY-tw>P0)tw=WY,Z$=0;if(Z$++,Z$>Z){R.error(`rpx: worker keeps exiting (code ${sw}); giving up after ${Z} restarts in ${Math.round(P0/1000)}s`);return}let ow=Math.min(S$,100*2**Math.min(Z$,8));N("daemon",`worker exited (code ${sw}); respawning in ${ow}ms (restart ${Z$}/${Z})`,B),setTimeout(Bw,ow).unref?.()}});q.push(hw)}for(let h=0;h<j;h++)Bw();if(B)R.success(`rpx coordinator listening on https://${U}:${X} via ${j} worker(s)${L?` (http→https on :${J})`:""}`),R.info(`pid file: ${z}`);let Sw,Zw=new Promise((h)=>{Sw=h});async function aw(){if(T)return Zw;if(T=!0,clearInterval(I),f.close(),L?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(q.map((h)=>h.exited)),new Promise((h)=>setTimeout(h,3000))]),E("SIGKILL"),await yw({rpxDir:Y,verbose:B}).catch((h)=>{N("daemon",`DNS teardown failed: ${h}`,B)}),await JY(Y),await u0.unlink(YB(Y)).catch(()=>{}),B)R.info("rpx coordinator stopped");return Sw(),Zw}let h$=(h)=>{N("daemon",`coordinator received ${h}, shutting down`,B),aw().catch(()=>{})};return Q.once("SIGINT",h$),Q.once("SIGTERM",h$),{stop:aw,done:Zw,httpsPort:X,httpPort:J,pidPath:z,ensureCert:(h)=>y?y.ensureCert(h):Promise.resolve(!1),listSites:()=>[]}}function J4(){let $=Q.execPath,w=O$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&Q.argv[1])return[$,Q.argv[1],"daemon:start"];return[$,"daemon:start"]}async function u6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1;await Uw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await Lw(w);if(A!==null&&b0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await JY(w);await u0.mkdir(w,{recursive:!0});let X=$.spawnCommand??J4();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=h6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??Q.cwd(),env:$.spawnEnv?{...Q.env,...$.spawnEnv}:Q.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await Lw(w);if(z!==null&&b0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}async function v6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1,A=$.timeoutMs??5000,X=$.pollIntervalMs??50,J=$.forceAfterTimeout??!0,U=await Lw(w);if(U===null||!b0(U)){if(U!==null)await JY(w);return await Uw({rpxDir:w,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{Q.kill(U,"SIGTERM")}catch(W){let j=W.code;if(j==="ESRCH")return await JY(w),{stopped:!1,pid:U,forced:!1};if(j==="EPERM")ww(`kill -TERM ${U}`);else throw W}let B=Date.now()+A;while(Date.now()<B){if(!b0(U))return N("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);N("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{Q.kill(U,"SIGKILL")}catch(W){let j=W.code;if(j==="EPERM")ww(`kill -KILL ${U}`);else if(j!=="ESRCH")throw W}return await JY(w),await yw({rpxDir:w,verbose:Y}).catch((W)=>{N("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function c6($={}){let w=$.rpxDir??w$();if(await r8(w))return;await Uw({rpxDir:w,verbose:$.verbose})}c$();X0();import{spawn as U4}from"node:child_process";import*as t8 from"node:process";class i6{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||t8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${H$(w.env)}`,Y);let U=U4(A,X,{cwd:J,env:{...t8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var a8=new i6;X0();import*as r0 from"node:fs/promises";import{homedir as W4}from"node:os";import*as AB from"node:path";import*as XB from"node:process";var B4=/^[a-zA-Z0-9._-]+$/;function rw(){return AB.join(W4(),".stacks","rpx","registry.d")}function UY($){return typeof $==="string"&&$.length>0&&$.length<=128&&B4.test($)}function JB($,w){if(!UY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return AB.join($,`${w}.json`)}function m6($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0||Array.isArray(w.from)&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&UY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function j4($){await r0.mkdir($,{recursive:!0})}async function g6($,w=rw(),Y){if(!m6($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await j4(w);let A=JB(w,$.id),X=`${A}.tmp.${XB.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await r0.writeFile(X,J,{encoding:"utf8",mode:420}),await r0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await r0.unlink(X).catch(()=>{}),U}}async function d6($,w=rw(),Y){let A=JB(w,$);try{await r0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function UB($,w=rw(),Y){let A=JB(w,$);try{let X=await r0.readFile(A,"utf8"),J=JSON.parse(X);if(!m6(J))return N("registry",`entry ${$} failed validation, removing`,Y),await r0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return N("registry",`entry ${$} has invalid JSON, removing`,Y),await r0.unlink(A).catch(()=>{}),null;throw X}}async function WB($=rw(),w){let Y;try{Y=await r0.readdir($)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!UY(J))continue;let U=await UB(J,$,w);if(U)A.push(U)}return A}c$();import{execSync as E4}from"node:child_process";import*as JJ from"node:http";import*as t6 from"node:net";import*as J0 from"node:process";var s8=($,w)=>(Y)=>`\x1B[${$}m${Y}\x1B[${w}m`,L$={bold:s8(1,22),dim:s8(2,22),green:s8(32,39),cyan:s8(36,39)};yW();d9();c$();lw();X0();import*as l6 from"node:fs";import*as n6 from"node:path";import*as _$ from"node:process";function z4($,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 BB($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,Y=$.registryDir,A=new Set,X=$.proxies.map((K)=>{let F=K.id??z4(K.to,K.path);if(!gY(F))throw Error(`invalid registry id "${F}" derived from to="${K.to}"`);if(A.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return A.add(F),{...K,id:F}}),J=new Date().toISOString();for(let K of X)await x8({id:K.id,from:K.from,to:K.to,path:K.path,pid:$.persistent?void 0:_$.pid,cwd:_$.cwd(),createdAt:J,cleanUrls:K.cleanUrls,changeOrigin:K.changeOrigin,pathRewrites:K.pathRewrites,static:K.static,loadBalancer:K.loadBalancer},Y,w);let U=await K6({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let K of X){let F=K.static?`static ${typeof K.static==="string"?K.static:K.static.dir}`:K.from;R.success(`https://${K.to} → ${F}`)}if(R.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let B=!1,W=Y??y$(),j=X.map((K)=>K.id),z=async()=>{if(B)return;B=!0;for(let K of j)await dY(K,Y,w).catch((F)=>{N("runner",`removeEntry(${K}) failed: ${F}`,w)})},G=(K)=>{N("runner",`received ${K}, unregistering ${j.length} entries`,w),z().finally(()=>_$.exit(0))};_$.once("SIGINT",G),_$.once("SIGTERM",G),_$.once("exit",()=>{if(B)return;for(let K of j)try{l6.unlinkSync(n6.join(W,`${K}.json`))}catch{}}),await new Promise(()=>{})}c8();V8();k9();c$();X0();import{spawn as G4}from"node:child_process";import*as o8 from"node:process";class e8{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||o8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${H$(w.env)}`,Y);let U=G4(A,X,{cwd:J,env:{...o8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var WS=new e8;import{timingSafeEqual as K4}from"node:crypto";function F4($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return K4(Y,A)}function $J($){return $.toLowerCase().replace(/\.$/,"")}var N4=["/.well-known/acme-challenge/"];function q4($){let w=$.headers.get("host");if(w)return $J(w.split(":")[0]);try{return $J(new URL($.url).hostname)}catch{return""}}function p6($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let W of $.hosts){let j=$J(W);if(j.startsWith("*."))A.push(j);else Y.add(j)}let X=$.exemptPaths??N4,J=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
338
|
-
`,U=(W)=>{let j=$J(W);return Y.has(j)||A.some((z)=>EY(j,z))},B=(W)=>{let j=q4(W);if(!U(j))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((G)=>z.startsWith(G)))return;if(F4(W.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return B.protects=U,B}O8();L8();xY();cY();S8();uY();X0();var YJ=new e8,T4="0.12.0",f4=new h8("0.0.0.0"),AJ=new Set,XJ=new Set,jB=!1,wJ=null,zB=null;async function UJ($){if(jB)return N("cleanup","Cleanup already in progress, skipping",$?.verbose),zB||Promise.resolve();jB=!0,N("cleanup","Starting cleanup process",$?.verbose),zB=new Promise((w)=>{wJ=w});try{await YJ.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from(AJ).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),N("cleanup","Bun server stopped",$?.verbose),X();else if(typeof J.close==="function")J.close(()=>{N("cleanup","Server closed successfully",$?.verbose),X()});else X()}catch(U){N("cleanup",`Error stopping server: ${U}`,$?.verbose),X()}}));w.push(...Y),AJ.clear();for(let A of XJ)gw(A);if(XJ.clear(),$?.hosts&&$.domains?.length){N("cleanup","Cleaning up hosts file entries",$?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(j6(A,$?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((X)=>{N("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){N("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(X)=>{try{await CG(X,$?.verbose),N("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){N("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),R.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...A)}await Promise.allSettled(w),N("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){N("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(wJ)wJ();wJ=null,jB=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!w)J0.exit(0)}return zB}var GB=!1;function a6($){if(GB){N("signal",`Received second ${$} signal, forcing exit`,!0),J0.exit(1);return}GB=!0,N("signal",`Received ${$} signal, initiating cleanup`,!0),UJ().catch((w)=>{N("signal",`Cleanup failed after ${$}: ${w}`,!0),J0.exit(1)}).finally(()=>{GB=!1})}J0.once("SIGINT",()=>a6("SIGINT"));J0.once("SIGTERM",()=>a6("SIGTERM"));J0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});J0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function eY($,w,Y,A=5){N("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((B,W)=>{let j=t6.connect({host:$,port:w,timeout:3000});j.once("connect",()=>{N("connection",`Successfully connected to ${$}:${w}`,Y),j.end(),B()}),j.once("timeout",()=>{N("connection",`Connection to ${$}:${w} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(z)=>{N("connection",`Failed to connect to ${$}:${w}: ${z}`,Y),j.destroy(),W(z)})});try{await U()}catch(B){let W=B;if(Date.now()-J>X){N("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),eY($,w,Y,A-1);if(A>0)try{N("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((z,G)=>{let K=JJ.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{N("connection",`Received HTTP response with status: ${F.statusCode}`,Y),z()});K.on("error",(F)=>G(F)),K.on("timeout",()=>{K.destroy(),G(Error("HTTP request timed out"))}),K.end()}),N("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(z){return N("connection",`HTTP request to ${$}:${w} failed: ${z}`,Y),N("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((G)=>setTimeout(G,2000)),eY($,w,Y,A-1)}let j=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${W.message}`;N("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(j),R.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function s6($){N("server",`Starting server with options: ${H$($)}`,$.verbose);let w=Vw($.from),Y=new URL(w.startsWith("http")?w:`http://${w}`),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(FB($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await tY(J,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await rY(J,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),J0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(B){R.error("Failed to check hosts file:",B.message)}}try{await eY(Y.hostname,X,$.verbose)}catch(B){N("server",`Connection test failed: ${B}`,$.verbose),R.error(B.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=hY({...$,to:A.hostname});if(U=await Yw({...$,to:A.hostname,https:$.https}),!U){if(N("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await d1({...$,from:Y.toString(),to:A.hostname,https:$.https}),U=await Yw({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(B){throw N("server",`SSL setup failed: ${B}`,$.verbose),B}N("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await R4({...$,from:w,originalFrom:$.from||w,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function H4($,w,Y,A,X,J,U,B,W,j,z,G){N("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,U);let K=l1(z??A.host,G);n1(K);let F=[{host:w,route:{sourceHost:A.host,upstreamPool:K,cleanUrls:B||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!KB({routeEntries:F,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw gw(K),Error(`Failed to start proxy server for ${w} on port ${Y}`);XJ.add(K),I4({from:$,to:w,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:B,verbose:U})}async function R4($){N("setup",`Setting up reverse proxy: ${H$($)}`,$.verbose);let{from:w,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:B,vitePluginUsage:W,changeOrigin:j,cleanUrls:z}=$,G=80,K=443,F="0.0.0.0",T=$.portManager||f4,q=FB($);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await tY([A],U))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await rY([A],U),R.success(`Added ${A} to your hosts file.`)}catch(C){R.error(`Failed to add ${A} to your hosts file: ${C}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(q&&J0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await tY([A],U))[0]){N("hosts",`${A} not found in hosts file, adding...`,U);try{await rY([A],U)}catch(C){N("hosts",`Failed to add ${A} to hosts file: ${C}`,U)}}}if(J&&!T.usedPorts.has(G)){if(!await Qw(G,F,U))N("setup","Starting HTTP redirect server",U),o6(U),T.usedPorts.add(G);else if(N("setup","Port 80 is in use, skipping HTTP redirect",U),U)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=J?K:G,H=await Qw(E,F,U),M;if(H){if(N("setup",`Port ${E} is already in use`,U),U)R.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(M=await T.getNextAvailablePort(3443,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at https://${A}:${M}`)}else if(M=await T.getNextAvailablePort(E+1000,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at http://${A}:${M}`)}else M=E,T.usedPorts.add(M),N("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await H4(w,A,M,X,J,W,U,z,j,p1($.auth),Y,$.loadBalancer)}catch(E){N("setup",`Setup failed: ${E}`,U),R.error(`Failed to setup reverse proxy: ${E.message}`),UJ({domains:[A],hosts:typeof B==="boolean"?B:B?.hosts,certs:typeof B==="boolean"?B:B?.certs,verbose:U,vitePluginUsage:W})}}function o6($,w=80,Y=443,A){N("redirect",`Starting HTTP redirect server on port ${w}`,$);let X=JJ.createServer((J,U)=>{if(A&&J.url){let z=J.url.split("?",1)[0],G=vY(A,z);if(G!=null){N("redirect",`Serving ACME challenge ${z}`,$),U.writeHead(200,{"content-type":"text/plain"}),U.end(G);return}}let B=J.headers.host||"",W=B.includes(":")?B.slice(0,B.indexOf(":")):B,j=Y===443?W:`${W}:${Y}`;N("redirect",`Redirecting request from ${B}${J.url} to https://${j}`,$),U.writeHead(301,{Location:`https://${j}${J.url}`}),U.end()}).listen(w);AJ.add(X),N("redirect","HTTP redirect server started",$)}function e6($){let w={...QW,...$};if(N("proxy",`Starting proxy with options: ${H$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}BB({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),J0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (AY(),d8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:w.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:hY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};N("proxy",`Server options: ${H$(B)}`,w.verbose),s6(B).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),UJ({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 M4($){return $?.verbose||!1}function FB($){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 $K($){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=M4(w),A=FB(w);if(N("config",`Starting with config: ${H$(w,2)}`,Y),N("config",`Is multi-proxy? ${"proxies"in w}`,Y),N("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let I="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((L)=>({id:L.id,from:L.from,to:L.to,path:L.path,cleanUrls:L.cleanUrls??w.cleanUrls,changeOrigin:L.changeOrigin??w.changeOrigin,pathRewrites:L.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 BB({proxies:I,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){N("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let f of w.proxies)if(f.start){let I=`${f.from}-${f.to}`;try{N("watch",`Starting command for ${I} with command: ${f.start.command}`,Y),R.info(`Starting command for ${I}...`),await YJ.startProcess(I,f.start,Y);let L=Vw(f.from),Z=new URL(L.startsWith("http")?L:`http://${L}`),P0=Z.hostname||"localhost",S$=Number(Z.port)||80;try{await eY(P0,S$,Y),N("watch",`Dev server is ready at ${P0}:${S$}`,Y)}catch(Z$){N("watch",`Connection check failed, but continuing with proxy setup: ${Z$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(L){throw N("watch",`Failed to start command for ${I}: ${L}`,Y),Error(`Failed to start command for ${I}: ${L}`)}}else N("watch",`No start command for proxy ${f.from} -> ${f.to}`,Y)}else if("start"in w&&w.start){N("watch","Found start command in single proxy config",Y);let f=`${w.from}-${w.to}`;try{if(w.start)N("watch",`Starting command: ${w.start.command}`,Y),await YJ.startProcess(f,w.start,Y);let I=Vw(w.from),L=new URL(I.startsWith("http")?I:`http://${I}`),Z=L.hostname||"localhost",P0=Number(L.port)||80;try{await eY(Z,P0,Y),N("watch",`Dev server is ready at ${Z}:${P0}`,Y)}catch(S$){N("watch",`Connection check failed, but continuing with proxy setup: ${S$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,Y),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",Y);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(J0.platform!=="win32"&&(w.https||A)){if(!iw())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",Y),E4("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if(w.productionCerts){if(J=await o1(w.productionCerts,Y),J.length>0)N("ssl",`Using ${J.length} production SNI cert(s): ${J.map((f)=>f.serverName).join(", ")}`,Y)}if(w.https){let f=J.length>0?null:await Yw(w);if(!f&&J.length===0){if(N("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await d1(w),f=await Yw(w),!f)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else N("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=f}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((f)=>({...f,https:w.https,cleanup:w.cleanup,cleanUrls:f.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:f.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,auth:"auth"in w?w.auth:void 0,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],B=U.map((f)=>f.to||"rpx.localhost"),W=J.length>0?J:w._cachedSSLConfig??null,j=B.filter((f)=>f&&!f.includes("localhost")&&!f.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"],K=[...new Set(j.map((f)=>f.split(".").pop()?.toLowerCase()))],F=K.filter((f)=>!!f&&z.includes(f));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((f)=>`.${f}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:f}=await Promise.resolve().then(() => (AY(),d8));if(await f({domains:j,verbose:Y})){if(Y)if(K.every((Z)=>!!Z&&G.includes(Z)))R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains`);else R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{N("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:f}=await Promise.resolve().then(() => (AY(),d8));await f({verbose:w.verbose})}catch(f){N("cleanup",`Error stopping DNS server: ${f}`,w.verbose)}try{await YJ.stopAll(w.verbose)}catch(f){N("cleanup",`Error stopping processes: ${f}`,w.verbose)}await UJ({domains:B,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};J0.on("SIGINT",T),J0.on("SIGTERM",T);let q=w.singlePortMode===!0,E=w.httpsPort??443,H=w.httpPort??80,M=w.originGuard?p6(w.originGuard):null,y=!!W&&(U.length>1||q||J.length>0),C=!W&&q&&U.length>0;if(y&&W){N("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let f=await r6(U,A,Y);if(!await Qw(H,"0.0.0.0",Y))o6(Y,H,E,w.acmeChallengeWebroot);if(await Qw(E,"0.0.0.0",Y)){if(N("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}if(!KB({routeEntries:f,listenPort:E,sslConfig:W,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(C){N("proxies",`Creating shared HTTP server for ${U.length} domains on port ${H}`,Y);let f=await r6(U,A,Y);if(await Qw(H,"0.0.0.0",Y)){if(N("proxies",`Port ${H} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${H} is in use. Shared HTTP proxy cannot start.`);return}if(!KB({routeEntries:f,listenPort:H,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${H}; not exiting`);return}}else for(let f of U)try{let I=f.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!W}`,f.verbose),await s6({from:f.from||"localhost:5173",to:I,cleanUrls:f.cleanUrls||!1,https:f.https||!1,cleanup:f.cleanup||!1,vitePluginUsage:f.vitePluginUsage||!1,verbose:f.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:f.changeOrigin||!1,loadBalancer:f.loadBalancer,auth:f.auth,path:f.path,pathRewrites:f.pathRewrites})}catch(I){N("proxies",`Failed to start proxy for ${f.to}: ${I}`,f.verbose),R.error(`Failed to start proxy for ${f.to}:`,I)}}async function r6($,w,Y){let A=[],X=new Set;for(let J of $){let U=J.to||"rpx.localhost",B=J.cleanUrls||!1,W=J.path,j=C$(W),z=p1(J.auth);if(J.redirect){let G=vG(J.redirect);A.push({host:U,path:W,route:{redirect:G,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → redirect ${G.status} ${G.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:bY(J.static,B),cleanUrls:B,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let G=Vw(J.from),K=new URL(G.startsWith("http")?G:`http://${G}`),F=l1(J.from??K.host,J.loadBalancer);n1(F),XJ.add(F),A.push({host:U,path:W,route:{sourceHost:K.host,upstreamPool:F,cleanUrls:B,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → ${K.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),w&&!F1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await tY([U],Y))[0])await rY([U],Y)}catch{N("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function KB($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=$,U=a1(w),B=r1((z,G)=>s1(U,z,G),J),W=X?(z,G)=>X(z)??B(z,G):B,j=t1(J);try{let z=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:i1(),...A?{tls:Array.isArray(A)?A.map((G)=>({serverName:G.serverName,key:G.key,cert:G.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(G,K){return W(G,K)},websocket:j,error(G){return N("server",`Shared proxy server error: ${G}`,J),new Response(`Server Error: ${G.message}`,{status:500})}});return AJ.add(z),N("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return N("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function I4($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${L$.green(L$.bold("rpx"))} ${L$.green(`v${T4}`)}`),console.log(` ${L$.green("➜")} ${L$.dim($?.from??"")} ${L$.dim("➜")} ${L$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${L$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${L$.green("➜")} Clean URLs enabled`)}z9();var bS=new cw("rpx",{showTags:!1});function wK($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}x0.chdir(C4(V4(Q4(import.meta.url)),".."));var v0=new HJ("rpx"),YK="0.12.0";v0.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 $K(K1);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),x0.exit(1)}w.start=Y}return e6(w)});v0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=wK(K1)?K1.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):K1.to===$?K1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),x0.exit(1);try{await a8.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),x0.exit(1)}});v0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await a8.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),x0.exit(1)}});v0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await a8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),x0.exit(1)}});async function AK($){let Y={...(await wz().catch(()=>null))?.onDemand??{},enabled:!0};if($){let A=$.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}v0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async($)=>{try{let w=$.onDemand?await AK($.roots):void 0;await(await b6({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,onDemandSites:w,verbose:$.verbose??!0})).done,x0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),x0.exit(1)}});v0.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 v6({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)":""}`)});v0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??w$(),Y=await Lw(w),A=await r8(w),X=$.registryDir,J=await WB(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:_w(w),rpxDir:w,registryDir:X??rw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${_w(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${_w(w)}`);if(console.log(`registry: ${X??rw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let B=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${B})`)}});v0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),x0.exit(1);if(!UY($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),x0.exit(1);try{await g6({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),x0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await u6({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),x0.exit(1)}});v0.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(!UY($))console.error(`invalid id: ${JSON.stringify($)}`),x0.exit(1);let Y=await UB($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await d6($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});v0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??w$();if(await r8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await c6({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});v0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async($)=>{let w=await AK($.roots),Y=Uz(w),A=await WB($.registryDir).catch(()=>[]),X=new Set(A.map((B)=>B.to)),J=Y.map((B)=>({host:B.host,dir:B.dir,command:B.command,source:B.source,live:X.has(B.host)}));if($.json){console.log(JSON.stringify(J,null,2));return}let U=w.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) \u2014 scanned ${U.join(", ")}:`);for(let B of J)console.log(` ${B.live?"\u25CF":"\u25CB"} https://${B.host} ${B.live?"(live)":"(idle)"}`),console.log(` ${B.command} ${B.dir}`)});v0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async($,w)=>{let{readFile:Y}=await import("fs/promises"),{join:A}=await import("path"),X=w.rpxDir??w$(),J=A(X,"sites",`${dA($.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${$} (it may not have been booted yet) \u2014 looked in ${J}`);return}let B=w.lines===void 0?void 0:typeof w.lines==="string"?Number.parseInt(w.lines,10):w.lines,W=U.split(`
|
|
339
|
-
`);
|
|
340
|
-
`))});
|
|
334
|
+
`)),this._prevFrame=w;return}this.output.write(TJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function zK(w,$){if(w===void 0)return 0;if($.length===0)return 0;let A=$.findIndex((X)=>X.value===w);return A!==-1?A:0}function GK(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function KK(w,$){if(!$)return;if(w)return $;return $[0]}class FK extends VJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return UA.inverse(UA.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let w=this.userInput.slice(0,this._cursor),[$,...Y]=this.userInput.slice(this._cursor);return`${w}${UA.inverse($)}${Y.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(w){super(w);this.#$=w.options;let $=this.options;this.filteredOptions=[...$],this.multiple=w.multiple===!0,this.#A=w.filter??GK;let Y;if(w.initialValue&&Array.isArray(w.initialValue))if(this.multiple)Y=w.initialValue;else Y=w.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let X=$.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#w=X}this.focusedValue=this.options[this.#w]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey(w,$){return w==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&w!==void 0&&w!==""}#X(w,$){let Y=$.name==="up",A=$.name==="down",X=$.name==="return";if(Y||A){if(this.#w=Math.max(0,Math.min(this.#w+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=KK(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(w){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(w))this.selectedValues=this.selectedValues.filter(($)=>$!==w);else this.selectedValues=[...this.selectedValues,w];else this.selectedValues=[w]}#J(w){if(w!==this.#Y){this.#Y=w;let $=this.options;if(w)this.filteredOptions=$.filter((Y)=>this.#A(w,Y));else this.filteredOptions=[...$];if(this.#w=zK(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class qK extends VJ{options;cursor=0;#w;getGroupItems(w){return this.options.filter(($)=>$.group===w)}isGroupSelected(w){let $=this.getGroupItems(w),Y=this.value;if(Y===void 0)return!1;return $.every((A)=>Y.includes(A.value))}toggleValue(){let w=this.options[this.cursor];if(this.value===void 0)this.value=[];if(w.group===!0){let $=String(w.value),Y=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((A)=>Y.findIndex((X)=>X.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(w.value);this.value=$?this.value.filter((Y)=>Y!==w.value):[...this.value,w.value]}}constructor(w){super(w,!1);let{options:$}=w;this.#w=w.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...w.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===w.cursorAt),this.#w?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var NK=V6();var e=(w,$)=>NK?w:$,$4=e("◆","*"),Y4=e("■","x"),A4=e("▲","x"),X4=e("◇","o"),J4=e("┌","T"),EK=e("│","|"),U4=e("└","—"),Q4=e("●",">"),W4=e("○"," "),B4=e("◻","[•]"),j4=e("◼","[+]"),z4=e("◻","[ ]"),G4=e("▪","•"),K4=e("─","-"),F4=e("╮","+"),q4=e("├","+"),N4=e("╯","+"),E4=e("●","•"),T4=e("◆","*"),f4=e("▲","!"),H4=e("■","x");var R4={light:e("─","-"),heavy:e("━","="),block:e("█","#")};function TK(){return`${UA.gray(EK)} `}var M4=TK();FU();import{homedir as qU}from"node:os";import{join as NU,resolve as OF}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",$9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:NU(qU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:NU(qU(),".stacks","ssl","stacks.localhost.crt"),keyPath:NU(qU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},EU=null;async function Y9(){if(!EU)EU=await KU({name:"rpx",cwd:OF(__dirname,".."),defaultConfig:$9});return EU}var K1=$9;import{existsSync as LF,readdirSync as _F,readFileSync as SF,statSync as ZF}from"node:fs";import{homedir as X9}from"node:os";import{isAbsolute as kF,join as q1}from"node:path";var J9=["~/Code"],U9=["localhost","test"],hF=1800000,TU={dirExists:(w)=>{try{return ZF(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return LF(w)}catch{return!1}},readText:(w)=>{try{return SF(w,"utf8")}catch{return null}}};function fU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return q1($,w.slice(2));return w}function DF(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function pA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function xF(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function PF(w,$){let Y=$.readText(q1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(q1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function bF(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function uF(w,$){let Y=PF(w,$);if(Y?.command)return bF(Y);let A=$.fileExists(q1(w,"buddy")),X=$.readText(q1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((Q)=>Q==="stacks"||Q.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function cF(w,$={}){let Y={dirExists:$.dirExists??TU.dirExists,fileExists:$.fileExists??TU.fileExists,readText:$.readText??TU.readText},A=$.detect??uF,X=$.homeDir??X9(),J=w.tlds??U9,U=(w.roots??J9).map((G)=>fU(G,X)),W=w.idleTimeoutMs??hF,Q=new Map;for(let G of w.sites??[])Q.set(G.to,G);let B=(G)=>G.idleTimeoutMs??W;function j(G){let K=nA(Q,G);if(!K)return null;let E=kF(K.dir)?K.dir:fU(K.dir,X),q=K.selfRegisters??!1,N=K.routes??[];if(!q&&N.length===0)N=A(E,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=A9({...K.env??{}},void 0,G);return{host:G,id:pA(G),dir:E,command:K.command,env:f,routes:N,selfRegisters:q,idleTimeoutMs:B(K),source:"config"}}function z(G){let K=xF(G,J);if(!K)return null;for(let E of U){let q=q1(E,K);if(!Y.dirExists(q))continue;let N=A(q,Y);if(!N)continue;let f=N.selfRegisters??!1;return{host:G,id:pA(G),dir:q,command:N.command,env:A9({...N.env??{}},N.urlEnv,G),routes:f?[]:N.routes??[],selfRegisters:f,idleTimeoutMs:W,source:"discovered"}}return null}return{resolve(G){let K=DF(G);if(!K)return null;return j(K)??z(K)}}}function vF(w){try{return _F(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function Q9(w,$={}){let Y=$.homeDir??X9(),A=w.tlds??U9,X=(w.roots??J9).map((z)=>fU(z,Y)),J=$.readdir??vF,U=cF(w,$),W=[],Q=new Set,B=(z)=>{if(z&&!Q.has(z.host))Q.add(z.host),W.push(z)};for(let z of w.sites??[])if(!z.to.includes("*"))B(U.resolve(z.to));let j=A[0]??"localhost";for(let z of X)for(let G of J(z))B(U.resolve(`${G}.${j}`));return W}function A9(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}lw();O8();Z8();k8();gY();D8();x8();DW();vW();iY();uY();r$();l8();XY();X0();import{spawn as D5}from"node:child_process";import*as u0 from"node:fs/promises";import{homedir as x5}from"node:os";import*as kw from"node:path";import*as C from"node:process";var YM=5000;function Aw(){return kw.join(x5(),".stacks","rpx")}function D$(w=Aw()){return kw.join(w,"daemon.pid")}async function h$(w=Aw()){try{let $=await u0.readFile(D$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function e8(w=Aw()){let $=await h$(w);return $!==null&&b0($)}async function P5(w=Aw()){await u0.mkdir(w,{recursive:!0});let $=D$(w);while(!0){try{let A=await u0.open($,"wx");try{await A.write(`${C.pid}
|
|
335
|
+
`)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await h$(w);if(Y!==null&&b0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await u0.unlink($).catch(()=>{})}}async function UY(w=Aw()){await u0.unlink(D$(w)).catch(()=>{})}var s8=new Map;function o8(w){for(let[$,Y]of s8)if(!w.has($))l$(Y),s8.delete($)}function AM(w,$){let Y=OW($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function b5(w){let $=w.cleanUrls??!1,Y=_w(w.path),A=r1(w.auth);if(w.static)return{static:vY(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=L$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),W=s8.get(w.id);if(W&&!AM(W,X))l$(W),W=void 0;if(!W)W=n1(X,w.loadBalancer),p1(W),s8.set(w.id,W);return{sourceHost:U.host,upstreamPool:W,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function XM(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function a8(w,$,Y=[],A=!1){let X=await Sw($,w.verbose),J=[...new Set([...X.map((j)=>j.to).filter(Boolean),...Y])],U=XM(J),W=[...new Set([U,...J,"rpx.localhost"])],Q=yW(J,U,w.verbose);if(typeof w.https==="object"&&typeof Q.https==="object")Q.https={...Q.https,...w.https};let B=await Q$(Q);if(B&&(A||!mX(C8,W)))F("daemon",`regenerating shared cert for host(s): ${W.join(", ")}`,w.verbose),y8(),B=null;if(!B)F("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await l1({...Q,forceRegenerate:!0}),B=await Q$(Q);if(!B)throw Error("failed to bootstrap TLS for rpx daemon");return B}async function JM(w,$,Y,A){let X=C.env.SUDO_PASSWORD,J=C.env.HOME??x5(),U=[C.execPath,...C.argv.slice(1)],W=[`HOME=${J}`,`PATH=${C.env.PATH??""}`];if(A)W.push("RPX_VERBOSE=1");for(let[E,q]of Object.entries(C.env))if(q!==void 0&&E!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(E))W.push(`${E}=${q}`);let Q=X?["-S","-p","","env",...W,...U]:["-n","env",...W,...U];F("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let B=D5("sudo",Q,{detached:!0,stdio:["pipe","ignore","ignore"]}),j=null,z=null;if(B.once("error",(E)=>{j=E}),B.once("exit",(E)=>{z=E??0}),X&&B.stdin)B.stdin.write(`${X}
|
|
336
|
+
`),B.stdin.end();B.unref();let G=D$(w),K=Date.now()+15000;while(Date.now()<K){if(j)throw j;let E=await h$(w);if(E!==null&&b0(E)){if(A)H.success(`rpx daemon elevated to root (pid=${E}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:G,done:Promise.resolve(),stop:async()=>{try{C.kill(E,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${$} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((q)=>setTimeout(q,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${w})`)}var Z5=!1;function AB(){if(Z5)return;Z5=!0,C.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),C.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function u5(w,$,Y){let A;try{A=new URL(w.url)}catch{return new Response("Bad Request",{status:400})}let X=(w.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if($){let J=$.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=mY(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if($)return new Response("challenge not found",{status:404})}if($&&!$.hasCert(X))$.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function c5(w={}){AB();let $=w.verbose??!1,Y=w.rpxDir??Aw(),A=w.registryDir??kw.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"0.0.0.0",W=w.gcIntervalMs??YM;if(C.env.RPX_DAEMON_WORKER==="1")return WM({rpxDir:C.env.RPX_WORKER_RPXDIR??Y,registryDir:C.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(C.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:C.env.RPX_WORKER_HOSTNAME??U,verbose:C.env.RPX_WORKER_VERBOSE==="1"||$});let Q=X>0&&X<1024||J>0&&J<1024,B=typeof C.getuid==="function"&&C.getuid()===0;if(C.platform!=="win32"&&Q&&!B)return JM(Y,X,J,$);let j=Math.max(1,w.workers??(Number.parseInt(C.env.RPX_WORKERS??"",10)||1));if(j>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return BM(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:W,workers:j})}let z=await P5(Y),G=new Map,K=(I,k)=>o1(G,I,k);function E(I){G=s1(I.map((Ow)=>({host:Ow.to,path:Ow.path,route:b5(Ow)}))),o8(new Set(I.map((Ow)=>Ow.id)));let k=Array.from(G.keys());F("daemon",`routing table now covers ${k.length} host(s): ${k.join(", ")||"<empty>"}`,$)}await $Y(A,$).catch((I)=>{F("daemon",`initial gc failed: ${I}`,$)}),await AY({verbose:$}).catch((I)=>{F("daemon",`stale hosts GC on start failed: ${I}`,$)});let q=await Sw(A,$);E(q),await z$({rpxDir:Y,verbose:$}).catch((I)=>{F("daemon",`DNS reconcile on start failed: ${I}`,$)}),await a$(q,{rpxDir:Y,verbose:$,ownerPid:C.pid}).catch((I)=>{F("daemon",`DNS setup on start failed: ${I}`,$)});let N=[];if(w.productionCerts){if(N=await e1(w.productionCerts,$),$&&N.length>0)H.info(`SNI: serving ${N.length} real cert(s): ${N.map((I)=>I.serverName).join(", ")}`)}let f=new Set,R=null,y;if(w.onDemandSites?.enabled){if(R=new i8({resolver:hW(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(I)=>h8(G,I)!==void 0,onSiteActivating:(I)=>{Cw(I)}}),y=async(I)=>{let k=await R.onRequest(I);switch(k.kind){case"ready":return{retry:!0};case"starting":return iW({host:k.host,sinceMs:k.sinceMs,logTail:k.logTail});case"failed":return mW({host:k.host,error:k.error,logTail:k.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let V=t1(K,$,y),T=a1($),M=null;if(N.length===0)M=await a8(w,A);let O=w.onDemandTls,S=O?.enabled?new p$({config:O,certsDir:O.certsDir??w.productionCerts?.certsDir??kw.join(Y,"on-demand-certs"),initial:N,verbose:$,onCertAdded:(I)=>{bw(I)}}):null;function B0(I){if(I.length>0)return I.map((k)=>({serverName:k.serverName,cert:k.cert,key:k.key}));return{key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1}}function a0(I){return Bun.serve({port:X,hostname:U,reusePort:m1(),tls:B0(I),fetch(k,Ow){return V(k,Ow)},websocket:T,error(k){return F("daemon",`https server error: ${k}`,$),new Response(`Server Error: ${k.message}`,{status:500})}})}let Kw=(I)=>[...new Set(I.map((k)=>k.to).filter(Boolean))],x$=(I)=>{if(!M)return N;return CW([...Kw(I),...f,"rpx.localhost"],M)},xw=a0(S?S.sniEntries():N.length>0?N:x$(q)),Pw=null,Fw=!1;async function bw(I){if(yw)return;if(Pw=I,Fw)return;Fw=!0;try{while(!yw&&Pw){let k=Pw;Pw=null,F("daemon",`rebuilding :443 with ${k.length} SNI cert(s)`,$),xw.stop(!1);let Ow,KJ=!1,NB=60,W6=500;for(let FJ=0;!yw&&!KJ;FJ++)try{xw=a0(k),KJ=!0;break}catch(B6){if(Ow=B6,FJ>=NB)break;await new Promise((j6)=>setTimeout(j6,Math.min(25*2**Math.min(FJ,4),W6)))}if(!KJ)H.error(`rpx: CRITICAL — could not rebind :443 after ${NB} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Ow?.message}`)}}finally{Fw=!1}}let s0=null;if(J>0)s0=Bun.serve({port:J,hostname:U,fetch(I){return u5(I,S,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${s0?` (http→https on :${J})`:""}`),H.info(`pid file: ${z}`),H.info(`registry: ${A}`);async function Z(I){if(yw||N.length>0||S||!M)return;try{M=await a8(w,A,[...f]),await bw(x$(I))}catch(k){F("daemon",`TLS sync on registry change failed: ${k}`,$)}}async function Cw(I){if(yw||N.length>0||S||!M||!I)return;if(f.has(I))return;f.add(I);try{M=await a8(w,A,[...f],!0);let k=await Sw(A,$);await bw(x$(k))}catch(k){F("daemon",`dev cert refresh for ${I} failed: ${k}`,$)}}let WY=pY((I)=>{E(I),Z(I),a$(I,{rpxDir:Y,verbose:$,ownerPid:C.pid}).catch((k)=>{F("daemon",`DNS sync on registry change failed: ${k}`,$)})},{dir:A,verbose:$}),o$=setInterval(()=>{$Y(A,$).then((I)=>{if(I>0)F("daemon",`gc reaped ${I} stale entries`,$)}).catch((I)=>{F("daemon",`periodic gc failed: ${I}`,$)}),AY({verbose:$}).then((I)=>{if(I.length>0)F("daemon",`gc reaped stale hosts entries: ${I.join(", ")}`,$)}).catch((I)=>{F("daemon",`periodic hosts gc failed: ${I}`,$)})},W);if(typeof o$.unref==="function")o$.unref();let yw=!1,BY,e$=new Promise((I)=>{BY=I});async function GJ(){if(yw)return e$;if(yw=!0,clearInterval(o$),WY.close(),await R?.stopAll().catch((I)=>{F("daemon",`site supervisor stopAll failed: ${I}`,$)}),xw.stop(!1),s0?.stop(!1),await Z$({rpxDir:Y,verbose:$}).catch((I)=>{F("daemon",`DNS teardown failed: ${I}`,$)}),o8(new Set),await UY(Y),$)H.info("rpx daemon stopped");return BY(),e$}let qB=(I)=>{F("daemon",`received ${I}, shutting down`,$),GJ().catch(()=>{})};return C.once("SIGINT",qB),C.once("SIGTERM",qB),{stop:GJ,done:e$,httpsPort:typeof xw.port==="number"?xw.port:X,httpPort:s0&&typeof s0.port==="number"?s0.port:J,pidPath:z,ensureCert:(I)=>S?S.ensureCert(I):Promise.resolve(!1),listSites:()=>R?.list()??[]}}function XB(w){return kw.join(w,"cluster-sni.json")}async function k5(w,$,Y){let A=XB(w),X=`${A}.${C.pid}.tmp`;await u0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await u0.rename(X,A)}async function h5(w){try{return JSON.parse(await u0.readFile(XB(w),"utf8"))}catch{return{sni:[],dev:null}}}function UM(w){if(w.sni.length>0)return w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key}));if(w.dev)return{key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function QM(){let w=C.execPath,$=C.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=kw.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&C.argv[1])return[w,C.argv[1],"daemon:start"];return[w,"daemon:start"]}async function WM(w){AB();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,W=(T,M)=>o1(U,T,M),Q=(T)=>{U=s1(T.map((M)=>({host:M.to,path:M.path,route:b5(M)}))),o8(new Set(T.map((M)=>M.id)))};Q(await Sw(Y,J));let B=t1(W,J),j=a1(J),z=!1,G=(T)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:UM(T),fetch(M,O){return B(M,O)},websocket:j,error(M){return F("daemon",`worker https error: ${M}`,J),new Response(`Server Error: ${M.message}`,{status:500})}}),K=G(await h5($));async function E(){if(z)return;let T=await h5($),M=null;for(let S=0;S<20&&!z;S++)try{M=G(T);break}catch{await new Promise((B0)=>setTimeout(B0,25))}if(!M){F("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let O=K;K=M,O.stop(!1)}let q=pY((T)=>Q(T),{dir:Y,verbose:J}),N=()=>{E().catch(()=>{})};C.on("SIGHUP",N);let f,R=new Promise((T)=>{f=T});async function y(){if(z)return R;return z=!0,C.off("SIGHUP",N),q.close(),K.stop(!1),o8(new Set),f(),R}let V=()=>{y().then(()=>C.exit(0)).catch(()=>C.exit(0))};if(C.once("SIGTERM",V),C.once("SIGINT",V),J)H.success(`rpx worker (pid ${C.pid}) serving :${A}`);return{stop:y,done:R,httpsPort:typeof K.port==="number"?K.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function BM(w,$){AB();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:W,gcIntervalMs:Q,workers:B}=$,j=await P5(Y),z=[];if(w.productionCerts)z=await e1(w.productionCerts,W);let G=null;if(z.length===0)G=await a8(w,A);let K=G?{key:G.key,cert:G.cert,ca:Array.isArray(G.ca)?G.ca.join(`
|
|
337
|
+
`):G.ca}:null,E=!1,q=[];function N(Z){for(let Cw of q)try{Cw.kill(Z)}catch{}}async function f(Z){await k5(Y,Z,K),N("SIGHUP")}let R=w.onDemandTls,y=R?.enabled?new p$({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??kw.join(Y,"on-demand-certs"),initial:z,verbose:W,onCertAdded:(Z)=>{f(Z)}}):null;await k5(Y,y?y.sniEntries():z,K);let V=await Sw(A,W);await z$({rpxDir:Y,verbose:W}).catch((Z)=>{F("daemon",`DNS reconcile on start failed: ${Z}`,W)}),await a$(V,{rpxDir:Y,verbose:W,ownerPid:C.pid}).catch((Z)=>{F("daemon",`DNS setup on start failed: ${Z}`,W)}),await $Y(A,W).catch(()=>{}),await AY({verbose:W}).catch(()=>{});let T=pY((Z)=>{a$(Z,{rpxDir:Y,verbose:W,ownerPid:C.pid}).catch((Cw)=>{F("daemon",`DNS sync on registry change failed: ${Cw}`,W)})},{dir:A,verbose:W}),M=setInterval(()=>{$Y(A,W).catch(()=>{}),AY({verbose:W}).catch(()=>{})},Q);M.unref?.();let O=null;if(J>0)O=Bun.serve({port:J,hostname:U,fetch(Z){return u5(Z,y,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let S=10,B0=60000,a0=30000,Kw=0,x$=Date.now();function xw(){if(E)return;let Z={...C.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:W?"1":"0"},Cw=Bun.spawn(QM(),{env:Z,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(WY,o$){if(E)return;let yw=q.indexOf(WY);if(yw!==-1)q.splice(yw,1);let BY=Date.now();if(BY-x$>B0)x$=BY,Kw=0;if(Kw++,Kw>S){H.error(`rpx: worker keeps exiting (code ${o$}); giving up after ${S} restarts in ${Math.round(B0/1000)}s`);return}let e$=Math.min(a0,100*2**Math.min(Kw,8));F("daemon",`worker exited (code ${o$}); respawning in ${e$}ms (restart ${Kw}/${S})`,W),setTimeout(xw,e$).unref?.()}});q.push(Cw)}for(let Z=0;Z<B;Z++)xw();if(W)H.success(`rpx coordinator listening on https://${U}:${X} via ${B} worker(s)${O?` (http→https on :${J})`:""}`),H.info(`pid file: ${j}`);let Pw,Fw=new Promise((Z)=>{Pw=Z});async function bw(){if(E)return Fw;if(E=!0,clearInterval(M),T.close(),O?.stop(!1),N("SIGTERM"),await Promise.race([Promise.all(q.map((Z)=>Z.exited)),new Promise((Z)=>setTimeout(Z,3000))]),N("SIGKILL"),await Z$({rpxDir:Y,verbose:W}).catch((Z)=>{F("daemon",`DNS teardown failed: ${Z}`,W)}),await UY(Y),await u0.unlink(XB(Y)).catch(()=>{}),W)H.info("rpx coordinator stopped");return Pw(),Fw}let s0=(Z)=>{F("daemon",`coordinator received ${Z}, shutting down`,W),bw().catch(()=>{})};return C.once("SIGINT",s0),C.once("SIGTERM",s0),{stop:bw,done:Fw,httpsPort:X,httpPort:J,pidPath:j,ensureCert:(Z)=>y?y.ensureCert(Z):Promise.resolve(!1),listSites:()=>[]}}function jM(){let w=C.execPath,$=kw.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&C.argv[1])return[w,C.argv[1],"daemon:start"];return[w,"daemon:start"]}async function v5(w={}){let $=w.rpxDir??Aw(),Y=w.verbose??!1;await z$({rpxDir:$,verbose:Y}).catch((j)=>{F("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await h$($);if(A!==null&&b0(A))return F("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)F("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await UY($);await u0.mkdir($,{recursive:!0});let X=w.spawnCommand??jM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");F("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=D5(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??C.cwd(),env:w.spawnEnv?{...C.env,...w.spawnEnv}:C.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=w.startupTimeoutMs??5000,Q=w.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await h$($);if(j!==null&&b0(j))return F("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,Q))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${$})`)}async function i5(w={}){let $=w.rpxDir??Aw(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await h$($);if(U===null||!b0(U)){if(U!==null)await UY($);return await z$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{C.kill(U,"SIGTERM")}catch(Q){let B=Q.code;if(B==="ESRCH")return await UY($),{stopped:!1,pid:U,forced:!1};if(B==="EPERM")U$(`kill -TERM ${U}`);else throw Q}let W=Date.now()+A;while(Date.now()<W){if(!b0(U))return F("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((Q)=>setTimeout(Q,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);F("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{C.kill(U,"SIGKILL")}catch(Q){let B=Q.code;if(B==="EPERM")U$(`kill -KILL ${U}`);else if(B!=="ESRCH")throw Q}return await UY($),await Z$({rpxDir:$,verbose:Y}).catch((Q)=>{F("daemon",`DNS teardown after SIGKILL: ${Q}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function m5(w={}){let $=w.rpxDir??Aw();if(await e8($))return;await z$({rpxDir:$,verbose:w.verbose})}lw();X0();import{spawn as zM}from"node:child_process";import*as wJ from"node:process";class g5{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){F("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||wJ.cwd();F("start",`Starting process ${w}:`,Y),F("start",` Command: ${A} ${X.join(" ")}`,Y),F("start",` Working directory: ${J}`,Y),F("start",` Environment variables: ${Iw($.env)}`,Y);let U=zM(A,X,{cwd:J,env:{...wJ.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((W,Q)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)F("start",`Process ${w} failed to start: ${B}`,Y),this.processes.delete(w),Q(B)}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)F("start",`Process ${w} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete(w),Q(Error(`Process ${w} exited with code ${B}`))}),Y)U.stdout?.on("data",(B)=>{F("process",`[${w}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{F("process",`[${w}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),Q(Error(`Process ${w} was killed during startup`));else F("start",`Process ${w} started successfully`,Y),W()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){F("start",`No process found for ${w}`,$);return}return F("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),F("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){F("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){F("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){F("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,F("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var $J=new g5;X0();import*as r0 from"node:fs/promises";import{homedir as GM}from"node:os";import*as JB from"node:path";import*as UB from"node:process";var KM=/^[a-zA-Z0-9._-]+$/;function s$(){return JB.join(GM(),".stacks","rpx","registry.d")}function QY(w){return typeof w==="string"&&w.length>0&&w.length<=128&&KM.test(w)}function QB(w,$){if(!QY($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return JB.join(w,`${$}.json`)}function d5(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&QY($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function FM(w){await r0.mkdir(w,{recursive:!0})}async function l5(w,$=s$(),Y){if(!d5(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await FM($);let A=QB($,w.id),X=`${A}.tmp.${UB.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await r0.writeFile(X,J,{encoding:"utf8",mode:420}),await r0.rename(X,A),F("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await r0.unlink(X).catch(()=>{}),U}}async function n5(w,$=s$(),Y){let A=QB($,w);try{await r0.unlink(A),F("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function WB(w,$=s$(),Y){let A=QB($,w);try{let X=await r0.readFile(A,"utf8"),J=JSON.parse(X);if(!d5(J))return F("registry",`entry ${w} failed validation, removing`,Y),await r0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return F("registry",`entry ${w} has invalid JSON, removing`,Y),await r0.unlink(A).catch(()=>{}),null;throw X}}async function BB(w=s$(),$){let Y;try{Y=await r0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!QY(J))continue;let U=await WB(J,w,$);if(U)A.push(U)}return A}lw();import{execSync as RM}from"node:child_process";import*as jJ from"node:http";import*as s5 from"node:net";import*as o5 from"node:os";import*as e5 from"node:path";import*as J0 from"node:process";var YJ=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,hw={bold:YJ(1,22),dim:YJ(2,22),green:YJ(32,39),cyan:YJ(36,39)};SQ();nW();lw();r$();X0();import*as p5 from"node:fs";import*as r5 from"node:path";import*as Dw from"node:process";function qM(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function jB(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((G)=>{let K=G.id??qM(G.to,G.path);if(!lY(K))throw Error(`invalid registry id "${K}" derived from to="${G.to}"`);if(A.has(K))throw Error(`duplicate registry id "${K}" — set an explicit \`id\` on one of the proxies`);return A.add(K),{...G,id:K}}),J=new Date().toISOString();for(let G of X)await v8({id:G.id,from:G.from,to:G.to,path:G.path,pid:w.persistent?void 0:Dw.pid,cwd:Dw.cwd(),createdAt:J,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin,pathRewrites:G.pathRewrites,static:G.static,loadBalancer:G.loadBalancer},Y,$);let U=await F5({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let G of X){let K=G.static?`static ${typeof G.static==="string"?G.static:G.static.dir}`:G.from;H.success(`https://${G.to} → ${K}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let W=!1,Q=Y??Zw(),B=X.map((G)=>G.id),j=async()=>{if(W)return;W=!0;for(let G of B)await nY(G,Y,$).catch((K)=>{F("runner",`removeEntry(${G}) failed: ${K}`,$)})},z=(G)=>{F("runner",`received ${G}, unregistering ${B.length} entries`,$),j().finally(()=>Dw.exit(0))};Dw.once("SIGINT",z),Dw.once("SIGTERM",z),Dw.once("exit",()=>{if(W)return;for(let G of B)try{p5.unlinkSync(r5.join(Q,`${G}.json`))}catch{}}),await new Promise(()=>{})}l8();O8();PW();lw();X0();import{spawn as NM}from"node:child_process";import*as AJ from"node:process";class XJ{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){F("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||AJ.cwd();F("start",`Starting process ${w}:`,Y),F("start",` Command: ${A} ${X.join(" ")}`,Y),F("start",` Working directory: ${J}`,Y),F("start",` Environment variables: ${Iw($.env)}`,Y);let U=NM(A,X,{cwd:J,env:{...AJ.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((W,Q)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)F("start",`Process ${w} failed to start: ${B}`,Y),this.processes.delete(w),Q(B)}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)F("start",`Process ${w} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete(w),Q(Error(`Process ${w} exited with code ${B}`))}),Y)U.stdout?.on("data",(B)=>{F("process",`[${w}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{F("process",`[${w}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),Q(Error(`Process ${w} was killed during startup`));else F("start",`Process ${w} started successfully`,Y),W()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){F("start",`No process found for ${w}`,$);return}return F("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),F("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){F("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){F("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){F("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,F("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var KS=new XJ;import{timingSafeEqual as EM}from"node:crypto";function TM(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return EM(Y,A)}function JJ(w){return w.toLowerCase().replace(/\.$/,"")}var fM=["/.well-known/acme-challenge/"];function HM(w){let $=w.headers.get("host");if($)return JJ($.split(":")[0]);try{return JJ(new URL(w.url).hostname)}catch{return""}}function t5(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let Q of w.hosts){let B=JJ(Q);if(B.startsWith("*."))A.push(B);else Y.add(B)}let X=w.exemptPaths??fM,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
338
|
+
`,U=(Q)=>{let B=JJ(Q);return Y.has(B)||A.some((j)=>TY(B,j))},W=(Q)=>{let B=HM(Q);if(!U(B))return;let j="/";try{j=new URL(Q.url).pathname}catch{}if(X.some((z)=>j.startsWith(z)))return;if(TM(Q.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=U,W}Z8();k8();uY();gY();D8();x8();iY();X0();var QJ=new XJ,MM="0.12.0",IM=new b8("0.0.0.0"),$A=new Set,BJ=new Set,zB=!1,UJ=null,GB=null;async function zJ(w){if(zB)return F("cleanup","Cleanup already in progress, skipping",w?.verbose),GB||Promise.resolve();zB=!0,F("cleanup","Starting cleanup process",w?.verbose),GB=new Promise(($)=>{UJ=$});try{await QJ.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from($A).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),F("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{F("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){F("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),$A.clear();for(let A of BJ)l$(A);if(BJ.clear(),w?.hosts&&w.domains?.length){F("cleanup","Cleaning up hosts file entries",w?.verbose),F("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(F("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(z5(A,w?.verbose).then(()=>{F("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{F("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){F("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await yG(X,w?.verbose),F("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){F("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),F("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){F("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(UJ)UJ();UJ=null,zB=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!$)J0.exit(0)}return GB}var KB=!1;function w6(w){if(KB){F("signal",`Received second ${w} signal, forcing exit`,!0),J0.exit(1);return}KB=!0,F("signal",`Received ${w} signal, initiating cleanup`,!0),zJ().catch(($)=>{F("signal",`Cleanup failed after ${w}: ${$}`,!0),J0.exit(1)}).finally(()=>{KB=!1})}J0.once("SIGINT",()=>w6("SIGINT"));J0.once("SIGTERM",()=>w6("SIGTERM"));J0.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});J0.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function YA(w,$,Y,A=5){F("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){F("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((W,Q)=>{let B=s5.connect({host:w,port:$,timeout:3000});B.once("connect",()=>{F("connection",`Successfully connected to ${w}:${$}`,Y),B.end(),W()}),B.once("timeout",()=>{F("connection",`Connection to ${w}:${$} timed out`,Y),B.destroy(),Q(Error("Connection timed out"))}),B.once("error",(j)=>{F("connection",`Failed to connect to ${w}:${$}: ${j}`,Y),B.destroy(),Q(j)})});try{await U()}catch(W){let Q=W;if(Date.now()-J>X){F("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(Q.code==="ECONNREFUSED"&&A>0)return F("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((j)=>setTimeout(j,2000)),YA(w,$,Y,A-1);if(A>0)try{F("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((j,z)=>{let G=jJ.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(K)=>{F("connection",`Received HTTP response with status: ${K.statusCode}`,Y),j()});G.on("error",(K)=>z(K)),G.on("timeout",()=>{G.destroy(),z(Error("HTTP request timed out"))}),G.end()}),F("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(j){return F("connection",`HTTP request to ${w}:${$} failed: ${j}`,Y),F("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),YA(w,$,Y,A-1)}let B=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${Q.message}`;F("connection",`${B}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(B),H.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function $6(w){F("server",`Starting server with options: ${Iw(w)}`,w.verbose);let $=L$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(FB(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){F("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await sY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await aY(J,w.verbose)}catch(Q){if(H.error("Failed to add hosts entry:",Q.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),J0.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else F("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(W){H.error("Failed to check hosts file:",W.message)}}try{await YA(Y.hostname,X,w.verbose)}catch(W){F("server",`Connection test failed: ${W}`,w.verbose),H.error(W.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=xY({...w,to:A.hostname});if(U=await Q$({...w,to:A.hostname,https:w.https}),!U){if(F("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await l1({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await Q$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(W){throw F("server",`SSL setup failed: ${W}`,w.verbose),W}F("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await CM({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function VM(w,$,Y,A,X,J,U,W,Q,B,j,z){F("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${W}`,U);let G=n1(j??A.host,z);p1(G);let K=[{host:$,route:{sourceHost:A.host,upstreamPool:G,cleanUrls:W||!1,changeOrigin:Q||!1,basePath:"/",auth:B}}];if(!WJ({routeEntries:K,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw l$(G),Error(`Failed to start proxy server for ${$} on port ${Y}`);BJ.add(G),OM({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:W,verbose:U})}async function CM(w){F("setup",`Setting up reverse proxy: ${Iw(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:W,vitePluginUsage:Q,changeOrigin:B,cleanUrls:j}=w,z=80,G=443,K="0.0.0.0",E=w.portManager||IM,q=FB(w);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await sY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await aY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(V){H.error(`Failed to add ${A} to your hosts file: ${V}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(q&&J0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await sY([A],U))[0]){F("hosts",`${A} not found in hosts file, adding...`,U);try{await aY([A],U)}catch(V){F("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!E.usedPorts.has(z)){if(!await S$(z,K,U))F("setup","Starting HTTP redirect server",U),Y6(U),E.usedPorts.add(z);else if(F("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let N=J?G:z,f=await S$(N,K,U),R;if(f){if(F("setup",`Port ${N} is already in use`,U),U)H.warn(`Port ${N} is already in use. This may be another instance of rpx or another service.`);if(N===443){if(R=await E.getNextAvailablePort(3443,!0),F("setup",`Using port ${R} instead of ${N}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await E.getNextAvailablePort(N+1000,!0),F("setup",`Using port ${R} instead of ${N}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=N,E.usedPorts.add(R),F("setup",`Using standard ${N===443?"HTTPS":"HTTP"} port ${N} for ${A}`,U);await VM($,A,R,X,J,Q,U,j,B,r1(w.auth),Y,w.loadBalancer)}catch(N){F("setup",`Setup failed: ${N}`,U),H.error(`Failed to setup reverse proxy: ${N.message}`),zJ({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:Q})}}function Y6(w,$=80,Y=443,A,X){F("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=jJ.createServer((U,W)=>{let Q=U.url?U.url.split("?",1)[0]:"";if(Q.startsWith("/.well-known/acme-challenge/")){if(X){let G=X.challengeStore.handlePath(Q);if(G!==void 0){F("redirect",`Serving on-demand ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(A){let G=mY(A,Q);if(G!=null){F("redirect",`Serving ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(X){W.writeHead(404,{"content-type":"text/plain"}),W.end("challenge not found");return}}let B=U.headers.host||"",j=B.includes(":")?B.slice(0,B.indexOf(":")):B;if(X&&j&&!X.hasCert(j))X.ensureCert(j).catch(()=>{});let z=Y===443?j:`${j}:${Y}`;F("redirect",`Redirecting request from ${B}${U.url} to https://${z}`,w),W.writeHead(301,{Location:`https://${z}${U.url}`}),W.end()}).listen($);$A.add(J),F("redirect","HTTP redirect server started",w)}function A6(w){let $={..._Q,...w};if(F("proxy",`Starting proxy with options: ${Iw($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}jB({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((Q)=>{H.error(`Failed to register with rpx daemon: ${Q.message}`),J0.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (XY(),t8)).then(({setupDevelopmentDns:Q})=>{Q({domains:[Y],verbose:$.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else F("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((Q)=>{F("dns",`Failed to start DNS server: ${Q}`,$.verbose)});let W={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:xY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};F("proxy",`Server options: ${Iw(W)}`,$.verbose),$6(W).catch((Q)=>{F("proxy",`Failed to start proxy: ${Q}`,$.verbose),H.error(`Failed to start proxy: ${Q.message}`),zJ({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function yM(w){return w?.verbose||!1}function FB(w){if(w?.hostsManagement===!1)return!1;let $=w?.cleanup;if($===!1)return!1;if($&&typeof $==="object"&&$.hosts===!1)return!1;return!0}async function X6(w){let $={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(w)$={...$,...w};let Y=yM($),A=FB($);if(F("config",`Starting with config: ${Iw($,2)}`,Y),F("config",`Is multi-proxy? ${"proxies"in $}`,Y),F("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let M="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??$.cleanUrls,changeOrigin:O.changeOrigin??$.changeOrigin,pathRewrites:O.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await jB({proxies:M,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){F("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let T of $.proxies)if(T.start){let M=`${T.from}-${T.to}`;try{F("watch",`Starting command for ${M} with command: ${T.start.command}`,Y),H.info(`Starting command for ${M}...`),await QJ.startProcess(M,T.start,Y);let O=L$(T.from),S=new URL(O.startsWith("http")?O:`http://${O}`),B0=S.hostname||"localhost",a0=Number(S.port)||80;try{await YA(B0,a0,Y),F("watch",`Dev server is ready at ${B0}:${a0}`,Y)}catch(Kw){F("watch",`Connection check failed, but continuing with proxy setup: ${Kw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw F("watch",`Failed to start command for ${M}: ${O}`,Y),Error(`Failed to start command for ${M}: ${O}`)}}else F("watch",`No start command for proxy ${T.from} -> ${T.to}`,Y)}else if("start"in $&&$.start){F("watch","Found start command in single proxy config",Y);let T=`${$.from}-${$.to}`;try{if($.start)F("watch",`Starting command: ${$.start.command}`,Y),await QJ.startProcess(T,$.start,Y);let M=L$($.from),O=new URL(M.startsWith("http")?M:`http://${M}`),S=O.hostname||"localhost",B0=Number(O.port)||80;try{await YA(S,B0,Y),F("watch",`Dev server is ready at ${S}:${B0}`,Y)}catch(a0){F("watch",`Connection check failed, but continuing with proxy setup: ${a0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw F("watch",`Failed to run start command: ${M}`,Y),Error(`Failed to run start command: ${M}`)}}else F("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(J0.platform!=="win32"&&($.https||A)){if(!I$())try{F("sudo","Pre-acquiring sudo credentials for privileged operations",Y),RM("sudo -v",{stdio:"inherit"})}catch{F("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await e1($.productionCerts,Y),J.length>0)F("ssl",`Using ${J.length} production SNI cert(s): ${J.map((T)=>T.serverName).join(", ")}`,Y)}if($.https){let T=J.length>0?null:await Q$($);if(!T&&J.length===0){if(F("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await l1($),T=await Q$($),!T)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else F("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=T}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((T)=>({...T,https:$.https,cleanup:$.cleanup,cleanUrls:T.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:T.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],W=U.map((T)=>T.to||"rpx.localhost"),Q=J.length>0?J:$._cachedSSLConfig??null,B=W.filter((T)=>T&&!T.includes("localhost")&&!T.includes("127.0.0.1")),j=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],G=[...new Set(B.map((T)=>T.split(".").pop()?.toLowerCase()))],K=G.filter((T)=>!!T&&j.includes(T));if(K.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${K.map((T)=>`.${T}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&B.length>0){let{setupDevelopmentDns:T}=await Promise.resolve().then(() => (XY(),t8));if(await T({domains:B,verbose:Y})){if(Y)if(G.every((S)=>!!S&&z.includes(S)))H.success(`DNS server started for ${G.map((S)=>`.${S}`).join(", ")} domains`);else H.success(`DNS server started for ${G.map((S)=>`.${S}`).join(", ")} domains (hosts file entries also added)`)}else F("dns","Could not start DNS server - custom domains may not resolve",Y)}let E=async()=>{F("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:T}=await Promise.resolve().then(() => (XY(),t8));await T({verbose:$.verbose})}catch(T){F("cleanup",`Error stopping DNS server: ${T}`,$.verbose)}try{await QJ.stopAll($.verbose)}catch(T){F("cleanup",`Error stopping processes: ${T}`,$.verbose)}await zJ({domains:W,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};J0.on("SIGINT",E),J0.on("SIGTERM",E);let q=$.singlePortMode===!0,N=$.httpsPort??443,f=$.httpPort??80,R=$.originGuard?t5($.originGuard):null,y=!!Q&&(U.length>1||q||J.length>0),V=!Q&&q&&U.length>0;if(y&&Q){F("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${N}`,Y);let T=await a5(U,A,Y),M=null,O=$.onDemandTls,S=O?.enabled?new p$({config:O,certsDir:O.certsDir??$.productionCerts?.certsDir??e5.join(o5.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(Fw)=>{Kw(Fw)}}):null,B0=null,a0=!1;async function Kw(Fw){if(B0=Fw,a0)return;a0=!0;try{while(B0){let bw=B0;if(B0=null,F("proxies",`rebuilding :${N} with ${bw.length} SNI cert(s)`,Y),M)$A.delete(M),M.stop(!1);let s0=!1;for(let Z=0;!s0&&Z<60;Z++){let Cw=WJ({routeEntries:T,listenPort:N,sslConfig:bw,originGuard:R,verbose:Y});if(Cw){M=Cw,s0=!0;break}await new Promise((WY)=>setTimeout(WY,Math.min(25*2**Math.min(Z,4),500)))}if(!s0)H.error(`rpx: CRITICAL — could not rebind :${N} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{a0=!1}}if(!await S$(f,"0.0.0.0",Y))Y6(Y,f,N,$.acmeChallengeWebroot,S);if(await S$(N,"0.0.0.0",Y)){if(F("proxies",`Port ${N} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${N} is in use. Shared HTTPS proxy cannot start.`);return}let Pw=S&&S.sniEntries().length>0?S.sniEntries():Q;if(M=WJ({routeEntries:T,listenPort:N,sslConfig:Pw,originGuard:R,verbose:Y}),!M){H.error(`Shared HTTPS proxy failed to bind :${N}; not exiting`);return}}else if(V){F("proxies",`Creating shared HTTP server for ${U.length} domains on port ${f}`,Y);let T=await a5(U,A,Y);if(await S$(f,"0.0.0.0",Y)){if(F("proxies",`Port ${f} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!WJ({routeEntries:T,listenPort:f,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let T of U)try{let M=T.to||"rpx.localhost";F("proxy",`Starting proxy for ${M} with SSL config: ${!!Q}`,T.verbose),await $6({from:T.from||"localhost:5173",to:M,cleanUrls:T.cleanUrls||!1,https:T.https||!1,cleanup:T.cleanup||!1,vitePluginUsage:T.vitePluginUsage||!1,verbose:T.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:T.changeOrigin||!1,loadBalancer:T.loadBalancer,auth:T.auth,path:T.path,pathRewrites:T.pathRewrites})}catch(M){F("proxies",`Failed to start proxy for ${T.to}: ${M}`,T.verbose),H.error(`Failed to start proxy for ${T.to}:`,M)}}async function a5(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",W=J.cleanUrls||!1,Q=J.path,B=_w(Q),j=r1(J.auth);if(J.redirect){let z=iG(J.redirect);A.push({host:U,path:Q,route:{redirect:z,basePath:B,auth:j}}),F("proxies",`Route: ${U}${Q??""} → redirect ${z.status} ${z.to}${j?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:Q,route:{static:vY(J.static,W),cleanUrls:W,basePath:B,auth:j}}),F("proxies",`Route: ${U}${Q??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${j?" (auth)":""}`,Y);else{let z=L$(J.from),G=new URL(z.startsWith("http")?z:`http://${z}`),K=n1(J.from??G.host,J.loadBalancer);p1(K),BJ.add(K),A.push({host:U,path:Q,route:{sourceHost:G.host,upstreamPool:K,cleanUrls:W,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:B,auth:j}}),F("proxies",`Route: ${U}${Q??""} → ${G.host}${j?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!F1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await sY([U],Y))[0])await aY([U],Y)}catch{F("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function WJ(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=s1($),W=t1((j,z)=>o1(U,j,z),J),Q=X?(j,z)=>X(j)??W(j,z):W,B=a1(J);try{let j=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:m1(),...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 Q(z,G)},websocket:B,error(z){return F("server",`Shared proxy server error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});return $A.add(j),F("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),j}catch(j){return F("proxies",`Failed to start shared proxy: ${j}`,J),console.error("Failed to start shared proxy:",j),null}}function OM(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${hw.green(hw.bold("rpx"))} ${hw.green(`v${MM}`)}`),console.log(` ${hw.green("➜")} ${hw.dim(w?.from??"")} ${hw.dim("➜")} ${hw.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${hw.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${hw.green("➜")} Clean URLs enabled`)}FW();var dS=new g$("rpx",{showTags:!1});function J6(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}P0.chdir(_M(LM(SM(import.meta.url)),".."));var c0=new IJ("rpx"),U6="0.12.0";c0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return X6(K1);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return A6($)});c0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=J6(K1)?K1.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):K1.to===w?K1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await $J.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});c0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await $J.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});c0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await $J.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function Q6(w){let Y={...(await Y9().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}c0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await Q6(w.roots):void 0;await(await c5({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});c0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await i5({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});c0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(w)=>{let $=w.rpxDir??Aw(),Y=await h$($),A=await e8($),X=w.registryDir,J=await BB(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:D$($),rpxDir:$,registryDir:X??s$(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${D$($)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${D$($)}`);if(console.log(`registry: ${X??s$()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});c0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!QY(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),P0.exit(1);try{await l5({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} \u2192 ${w.from} (daemon spawn skipped)`);return}try{let $=await v5({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} \u2192 ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});c0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(w,$)=>{if(!QY(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await WB(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await n5(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});c0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(w)=>{let $=w.rpxDir??Aw();if(await e8($)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await m5({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});c0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await Q6(w.roots),Y=Q9($),A=await BB(w.registryDir).catch(()=>[]),X=new Set(A.map((W)=>W.to)),J=Y.map((W)=>({host:W.host,dir:W.dir,command:W.command,source:W.source,live:X.has(W.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) \u2014 scanned ${U.join(", ")}:`);for(let W of J)console.log(` ${W.live?"\u25CF":"\u25CB"} https://${W.host} ${W.live?"(live)":"(idle)"}`),console.log(` ${W.command} ${W.dir}`)});c0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("fs/promises"),{join:A}=await import("path"),X=$.rpxDir??Aw(),J=A(X,"sites",`${pA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) \u2014 looked in ${J}`);return}let W=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,Q=U.split(`
|
|
339
|
+
`);P0.stdout.write((W&&W>0?Q.slice(-W):Q).join(`
|
|
340
|
+
`))});c0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(U6)});c0.version(U6);c0.help();c0.run();
|