@stacksjs/rpx 0.11.41 → 0.11.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import{createRequire as r6}from"node:module";var n6=Object.defineProperty;var l6=(w)=>w;function p6(w,$){this[w]=l6.bind(null,$)}var ej=(w,$)=>{for(var Y in $)n6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:p6.bind($,Y)})};var s=(w,$)=>()=>(w&&($=w(w=0)),$);var i=r6(import.meta.url);import{existsSync as KQ,statSync as FQ}from"fs";import{existsSync as eG,mkdirSync as PM,readdirSync as iM,readFileSync as w5,writeFileSync as bM}from"fs";import{homedir as p$}from"os";import{dirname as vM,resolve as Uw}from"path";import kA from"process";import{existsSync as TQ,statSync as NQ}from"fs";import{existsSync as ZJ,mkdirSync as $5,readdirSync as Y5,writeFileSync as A5}from"fs";import{homedir as r$}from"os";import{dirname as qQ,resolve as v0}from"path";import O$ from"process";import{join as X5,relative as J5,resolve as HQ}from"path";import RA from"process";import{existsSync as Af,mkdirSync as sM,readdirSync as oM,writeFileSync as eM}from"fs";import{homedir as KJ}from"os";import{dirname as Yy,resolve as c0}from"path";import a1 from"process";import{join as U5,relative as W5,resolve as RQ}from"path";import MA from"process";import{existsSync as Xf,mkdirSync as Wy,readdirSync as jy,writeFileSync as Qy}from"fs";import{dirname as zy,resolve as yA}from"path";import PJ from"process";import{Buffer as j$}from"buffer";import{createCipheriv as j5,createDecipheriv as Q5,randomBytes as FJ}from"crypto";import{closeSync as TJ,createReadStream as MQ,createWriteStream as f5,existsSync as NJ,fsyncSync as yQ,openSync as IQ,writeFileSync as z5}from"fs";import{access as B5,constants as CQ,mkdir as G5,readdir as $A,rename as VQ,stat as t$,unlink as YA,writeFile as qJ}from"fs/promises";import{join as a$}from"path";import L0 from"process";import{pipeline as E5}from"stream/promises";import{createGzip as LQ}from"zlib";import s$ from"process";import Pw from"process";import{Buffer as kw}from"buffer";import{createCipheriv as K5,createDecipheriv as F5,randomBytes as HJ}from"crypto";import{closeSync as RJ,createReadStream as SQ,createWriteStream as T5,existsSync as AA,fsyncSync as OQ,openSync as hQ,writeFileSync as N5}from"fs";import{access as q5,constants as _Q,mkdir as H5,readdir as XA,rename as DQ,stat as o$,unlink as JA,writeFile as MJ}from"fs/promises";import{isAbsolute as R5,join as e$,resolve as M5}from"path";import x from"process";import{pipeline as y5}from"stream/promises";import{createGzip as xQ}from"zlib";import w1 from"process";import iw from"process";import UA from"process";import{existsSync as WA}from"fs";import{resolve as yJ}from"path";import{existsSync as I5}from"fs";import{existsSync as C5,readdirSync as V5}from"fs";import{extname as IJ,resolve as kQ}from"path";import L5 from"process";import{join as S5,relative as O5,resolve as ZQ}from"path";import IA from"process";import{Buffer as Zw}from"buffer";import{createCipheriv as h5,createDecipheriv as _5,randomBytes as CJ}from"crypto";import{closeSync as VJ,createReadStream as PQ,createWriteStream as D5,existsSync as jA,fsyncSync as iQ,openSync as bQ,writeFileSync as x5}from"fs";import{access as k5,constants as uQ,mkdir as Z5,readdir as QA,rename as cQ,stat as $1,unlink as fA,writeFile as LJ}from"fs/promises";import{isAbsolute as P5,join as Y1,resolve as i5}from"path";import k from"process";import{pipeline as b5}from"stream/promises";import{createGzip as vQ}from"zlib";import A1 from"process";import bw from"process";import BA from"process";import{existsSync as GA}from"fs";import{resolve as xJ}from"path";import{existsSync as XK}from"fs";class $f{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!KQ(w))return!0;return FQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=KQ(Y)?FQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Yf{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 v5(w,$){this[w]=c5.bind(null,$)}class rJ{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(!TQ(w))return!0;return NQ(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=TQ(Y)?NQ(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 tJ{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 d5(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function n5(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function l5(w){return w.getStats().size*2}function aJ(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)=>CA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!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]=aJ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((W)=>Y0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((W)=>Y0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>CA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function CA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!CA(w[Y],$[Y]))return!1;return!0}if(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(!CA(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function p5(w,$){if(!Xf(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 aJ($,A)}catch{return null}}catch{return null}}async function r5({name:w="",cwd:$,defaultConfig:Y}){let A=$||PJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=yA(A,`${U}${j}`),Q=await p5(W,Y);if(Q!==null)return Q}try{let U=yA(A,"package.json");if(Xf(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return aJ(Y,W)}catch{}}}catch{}return Y}function t5(w,$={}){let Y=MA.cwd();while(Y.includes("storage"))Y=RQ(Y,"..");let A=RQ(Y,w||"");if($?.relative)return W5(MA.cwd(),A);return A}async function a5(){try{let w=await r5({name:"clarity",defaultConfig:FA,cwd:MA.cwd(),endpoint:"",headers:{}});return{...FA,...w}}catch{return FA}}function U0(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function s5(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pw<"u"){let w=Pw.type;if(w==="renderer"||w==="worker")return!1;return!!(Pw.versions&&(Pw.versions.node||Pw.versions.bun))}return!1}class Uf{async format(w){let $=await s5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:s$.pid,hostname:$(),environment:s$.env.NODE_ENV||"development",platform:s$.platform,version:s$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:s$.env.NODE_ENV||s$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class VA{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={...bJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Uf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...TA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...TA};return{...TA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:bJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await B5(this.config.logDirectory,CQ.F_OK|CQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await G5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:j$.from(w);try{if(!NJ(this.currentLogFile))await qJ(this.currentLogFile,"",{mode:420});if(X=IQ(this.currentLogFile,"a",420),z5(X,W,{flag:"a"}),yQ(X),X!==void 0)TJ(X),X=void 0;if((await t$(this.currentLogFile)).size===0){if(await qJ(this.currentLogFile,W,{flag:"w",mode:420}),(await t$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{TJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return a$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return a$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return a$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return FJ(16).toString("hex")}generateKey(){return FJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=FJ(16),A=j5("aes-256-gcm",$,Y),X=j$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:j$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=LQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(j$.from(j$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await t$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await $A(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await t$(Y).catch(()=>null))try{if(await VQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await YA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await qJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await t$(Y).catch(()=>null))await VQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await $A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await YA(a$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=MQ(w),A=f5($),X=LQ();await E5(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()})),NJ(this.currentLogFile))try{let w=IQ(this.currentLogFile,"r+");yQ(w),TJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await $A(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await YA(a$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=L0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${o.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let Q=Ff[w],f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
|
|
2
|
+
import{createRequire as r6}from"node:module";var n6=Object.defineProperty;var l6=(w)=>w;function p6(w,$){this[w]=l6.bind(null,$)}var ej=(w,$)=>{for(var Y in $)n6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:p6.bind($,Y)})};var s=(w,$)=>()=>(w&&($=w(w=0)),$);var i=r6(import.meta.url);import{existsSync as KQ,statSync as FQ}from"fs";import{existsSync as eG,mkdirSync as PM,readdirSync as iM,readFileSync as w5,writeFileSync as bM}from"fs";import{homedir as p$}from"os";import{dirname as vM,resolve as Uw}from"path";import kA from"process";import{existsSync as TQ,statSync as qQ}from"fs";import{existsSync as ZJ,mkdirSync as $5,readdirSync as Y5,writeFileSync as A5}from"fs";import{homedir as r$}from"os";import{dirname as NQ,resolve as v0}from"path";import O$ from"process";import{join as X5,relative as J5,resolve as HQ}from"path";import RA from"process";import{existsSync as Af,mkdirSync as sM,readdirSync as oM,writeFileSync as eM}from"fs";import{homedir as KJ}from"os";import{dirname as Yy,resolve as c0}from"path";import a1 from"process";import{join as U5,relative as W5,resolve as RQ}from"path";import MA from"process";import{existsSync as Xf,mkdirSync as Wy,readdirSync as jy,writeFileSync as Qy}from"fs";import{dirname as zy,resolve as yA}from"path";import PJ from"process";import{Buffer as j$}from"buffer";import{createCipheriv as j5,createDecipheriv as Q5,randomBytes as FJ}from"crypto";import{closeSync as TJ,createReadStream as MQ,createWriteStream as f5,existsSync as qJ,fsyncSync as yQ,openSync as IQ,writeFileSync as z5}from"fs";import{access as B5,constants as CQ,mkdir as G5,readdir as $A,rename as VQ,stat as t$,unlink as YA,writeFile as NJ}from"fs/promises";import{join as a$}from"path";import L0 from"process";import{pipeline as E5}from"stream/promises";import{createGzip as LQ}from"zlib";import s$ from"process";import Pw from"process";import{Buffer as kw}from"buffer";import{createCipheriv as K5,createDecipheriv as F5,randomBytes as HJ}from"crypto";import{closeSync as RJ,createReadStream as SQ,createWriteStream as T5,existsSync as AA,fsyncSync as OQ,openSync as hQ,writeFileSync as q5}from"fs";import{access as N5,constants as _Q,mkdir as H5,readdir as XA,rename as DQ,stat as o$,unlink as JA,writeFile as MJ}from"fs/promises";import{isAbsolute as R5,join as e$,resolve as M5}from"path";import x from"process";import{pipeline as y5}from"stream/promises";import{createGzip as xQ}from"zlib";import w1 from"process";import iw from"process";import UA from"process";import{existsSync as WA}from"fs";import{resolve as yJ}from"path";import{existsSync as I5}from"fs";import{existsSync as C5,readdirSync as V5}from"fs";import{extname as IJ,resolve as kQ}from"path";import L5 from"process";import{join as S5,relative as O5,resolve as ZQ}from"path";import IA from"process";import{Buffer as Zw}from"buffer";import{createCipheriv as h5,createDecipheriv as _5,randomBytes as CJ}from"crypto";import{closeSync as VJ,createReadStream as PQ,createWriteStream as D5,existsSync as jA,fsyncSync as iQ,openSync as bQ,writeFileSync as x5}from"fs";import{access as k5,constants as uQ,mkdir as Z5,readdir as QA,rename as cQ,stat as $1,unlink as fA,writeFile as LJ}from"fs/promises";import{isAbsolute as P5,join as Y1,resolve as i5}from"path";import k from"process";import{pipeline as b5}from"stream/promises";import{createGzip as vQ}from"zlib";import A1 from"process";import bw from"process";import BA from"process";import{existsSync as GA}from"fs";import{resolve as xJ}from"path";import{existsSync as XK}from"fs";class $f{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!KQ(w))return!0;return FQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=KQ(Y)?FQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Yf{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 v5(w,$){this[w]=c5.bind(null,$)}class rJ{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(!TQ(w))return!0;return qQ(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=TQ(Y)?qQ(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 tJ{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 d5(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function n5(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function l5(w){return w.getStats().size*2}function aJ(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)=>CA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!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]=aJ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((W)=>Y0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((W)=>Y0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>CA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function CA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!CA(w[Y],$[Y]))return!1;return!0}if(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(!CA(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function p5(w,$){if(!Xf(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 aJ($,A)}catch{return null}}catch{return null}}async function r5({name:w="",cwd:$,defaultConfig:Y}){let A=$||PJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=yA(A,`${U}${j}`),Q=await p5(W,Y);if(Q!==null)return Q}try{let U=yA(A,"package.json");if(Xf(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return aJ(Y,W)}catch{}}}catch{}return Y}function t5(w,$={}){let Y=MA.cwd();while(Y.includes("storage"))Y=RQ(Y,"..");let A=RQ(Y,w||"");if($?.relative)return W5(MA.cwd(),A);return A}async function a5(){try{let w=await r5({name:"clarity",defaultConfig:FA,cwd:MA.cwd(),endpoint:"",headers:{}});return{...FA,...w}}catch{return FA}}function U0(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function s5(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pw<"u"){let w=Pw.type;if(w==="renderer"||w==="worker")return!1;return!!(Pw.versions&&(Pw.versions.node||Pw.versions.bun))}return!1}class Uf{async format(w){let $=await s5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:s$.pid,hostname:$(),environment:s$.env.NODE_ENV||"development",platform:s$.platform,version:s$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:s$.env.NODE_ENV||s$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class VA{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={...bJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Uf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...TA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...TA};return{...TA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:bJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await B5(this.config.logDirectory,CQ.F_OK|CQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await G5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:j$.from(w);try{if(!qJ(this.currentLogFile))await NJ(this.currentLogFile,"",{mode:420});if(X=IQ(this.currentLogFile,"a",420),z5(X,W,{flag:"a"}),yQ(X),X!==void 0)TJ(X),X=void 0;if((await t$(this.currentLogFile)).size===0){if(await NJ(this.currentLogFile,W,{flag:"w",mode:420}),(await t$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{TJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return a$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return a$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return a$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return FJ(16).toString("hex")}generateKey(){return FJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=FJ(16),A=j5("aes-256-gcm",$,Y),X=j$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:j$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=LQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(j$.from(j$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await t$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await $A(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await t$(Y).catch(()=>null))try{if(await VQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await YA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await NJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await t$(Y).catch(()=>null))await VQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await $A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await YA(a$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=MQ(w),A=f5($),X=LQ();await E5(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()})),qJ(this.currentLogFile))try{let w=IQ(this.currentLogFile,"r+");yQ(w),TJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await $A(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await YA(a$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=L0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${o.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let Q=Ff[w],f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
|
|
3
3
|
`);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
|
|
4
4
|
`;if(j)W+=`${j}
|
|
5
5
|
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:o.blue("◐"),tag:Y,message:`${o.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
|
|
6
|
-
`,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:o.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(Q.trim());await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new VA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!
|
|
6
|
+
`,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:o.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(Q.trim());await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new VA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!qJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return MQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=j$.isBuffer(w)?w:j$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=Q5("aes-256-gcm",Y,X);return j.setAuthTag(J),j$.concat([j.update(U),j.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!U0()){let J=w.split(`
|
|
7
7
|
`),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:o.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
|
|
8
8
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(U0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();L0.stdin.removeListener("data",Y);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",j=o.blue("◐");console.error(`${j} ${U} ${o.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
9
9
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||U0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;L0.stdout.write(`${"\r".padEnd(L0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?o.green("✓"):o.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=L0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,L0.stdout.write(w.lastRenderedLine),$)L0.stdout.write(`
|
|
10
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await $A(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=a$(this.config.logDirectory,A);if(w.before)try{if((await t$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await YA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function KA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&l($[0])&&"id"in $[0]&&$[0].id===3&&l($[1])&&"id"in $[1]&&$[1].id===4)return $;if(l($)&&l(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(l(w)&&"arr"in w&&Array.isArray(w.arr)&&l($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&l($[0])&&l(w[0])){let A=[...$];for(let X of w)if(l(X)&&"name"in X){if(!A.find((U)=>l(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(l(X)&&"path"in X){if(!A.find((U)=>l(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>LA(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(!l($)||!l(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(l(X)&&l(Y[A]))Y[A]=KA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&l(X[0])&&l(Y[A][0])){let J=[...X];for(let U of Y[A])if(l(U)&&"name"in U){if(!J.find((W)=>l(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(l(U)&&"path"in U){if(!J.find((W)=>l(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>LA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function sJ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:KA(w,$);if(Array.isArray(w))return Y==="replace"?$:KA(w,$);if(!l($)||!l(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]=KA(U,J);else if(l(J)&&l(U))A[X]=sJ(U,J,Y);else A[X]=J}return A}function LA(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(!LA(w[Y],$[Y]))return!1;return!0}if(l(w)&&l($)){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(!LA(w[X],$[X]))return!1}return!0}return!1}function l(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function zA(w,$,Y="replace"){if(!Af(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 sJ($,X,Y)}catch{return null}}catch{return null}}function o5(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)O0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=a1.env[G]||a1.env[T];if(K!==void 0){if(Y)O0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function e5({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?o5(w,X,J):X,Q=Y||a1.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)O0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,c0(Q,"config"),c0(Q,".config"),A?c0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)O0.info(`Searching for configuration in: ${F}`);let R=[c0(Q,"config"),c0(Q,".config")].concat(A?[c0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let V of R)for(let L of f){let q=c0(F,`${V}${L}`),C=await zA(q,W,j);if(C!==null){if(J)O0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let F=c0(KJ(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)O0.info(`Checking user config directory: ${F}`);for(let R of N)for(let V of f){let L=c0(F,`${R}${V}`),q=await zA(L,W,j);if(q!==null){if(J)O0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let F=c0(KJ(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)O0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=c0(F,`${R}${V}`),q=await zA(L,W,j);if(q!==null){if(J)O0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let F=KJ(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)O0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=c0(F,`${R}${V}`),q=await zA(L,W,j);if(q!==null){if(J)O0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let F=c0(Q,"package.json");if(Af(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)O0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)O0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return sJ(W,R,j)}catch(V){if(J)O0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)O0.warn("Failed to load package.json:",F)}if(J)O0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function wE(w,$={}){let Y=RA.cwd();while(Y.includes("storage"))Y=HQ(Y,"..");let A=HQ(Y,w||"");if($?.relative)return J5(RA.cwd(),A);return A}async function $E(){try{let w=await e5({name:"clarity",alias:"logging",defaultConfig:NA,cwd:RA.cwd()});return{...NA,...w||{}}}catch{return NA}}function E0(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YE(){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 Wf{async format(w){let $=await YE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:w1.pid,hostname:$(),environment:w1.env.NODE_ENV||"development",platform:w1.platform,version:w1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:w1.env.NODE_ENV||w1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class SA{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={...uJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Wf,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{...qA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...qA};return{...qA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await q5(this.config.logDirectory,_Q.F_OK|_Q.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await H5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:kw.from(w);try{if(!AA(this.currentLogFile))await MJ(this.currentLogFile,"",{mode:420});if(X=hQ(this.currentLogFile,"a",420),N5(X,W,{flag:"a"}),OQ(X),X!==void 0)RJ(X),X=void 0;if((await o$(this.currentLogFile)).size===0){if(await MJ(this.currentLogFile,W,{flag:"w",mode:420}),(await o$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{RJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return e$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return e$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return e$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return HJ(16).toString("hex")}generateKey(){return HJ(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=HJ(16),A=K5("aes-256-gcm",$,Y),X=kw.isBuffer(w)?w:kw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=kw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=xQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(kw.from(kw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await o$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await XA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await o$(Y).catch(()=>null))try{if(await DQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await JA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await MJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await o$(Y).catch(()=>null))await DQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await XA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await JA(e$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=SQ(w),A=T5($),X=xQ();await y5(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=hQ(this.currentLogFile,"r+");OQ(w),RJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await XA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await JA(e$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?b.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${b.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=b.underline(b.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(R5($)||$.startsWith("./")||$.startsWith("../"))$=M5($);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,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Tf[w],B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
10
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await $A(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=a$(this.config.logDirectory,A);if(w.before)try{if((await t$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await YA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function KA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&l($[0])&&"id"in $[0]&&$[0].id===3&&l($[1])&&"id"in $[1]&&$[1].id===4)return $;if(l($)&&l(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(l(w)&&"arr"in w&&Array.isArray(w.arr)&&l($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&l($[0])&&l(w[0])){let A=[...$];for(let X of w)if(l(X)&&"name"in X){if(!A.find((U)=>l(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(l(X)&&"path"in X){if(!A.find((U)=>l(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>LA(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(!l($)||!l(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(l(X)&&l(Y[A]))Y[A]=KA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&l(X[0])&&l(Y[A][0])){let J=[...X];for(let U of Y[A])if(l(U)&&"name"in U){if(!J.find((W)=>l(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(l(U)&&"path"in U){if(!J.find((W)=>l(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>LA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function sJ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:KA(w,$);if(Array.isArray(w))return Y==="replace"?$:KA(w,$);if(!l($)||!l(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]=KA(U,J);else if(l(J)&&l(U))A[X]=sJ(U,J,Y);else A[X]=J}return A}function LA(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(!LA(w[Y],$[Y]))return!1;return!0}if(l(w)&&l($)){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(!LA(w[X],$[X]))return!1}return!0}return!1}function l(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function zA(w,$,Y="replace"){if(!Af(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 sJ($,X,Y)}catch{return null}}catch{return null}}function o5(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)O0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=a1.env[G]||a1.env[T];if(K!==void 0){if(Y)O0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((q)=>q.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function e5({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?o5(w,X,J):X,Q=Y||a1.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)O0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,c0(Q,"config"),c0(Q,".config"),A?c0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)O0.info(`Searching for configuration in: ${F}`);let R=[c0(Q,"config"),c0(Q,".config")].concat(A?[c0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let V of R)for(let L of f){let N=c0(F,`${V}${L}`),C=await zA(N,W,j);if(C!==null){if(J)O0.success(`Configuration loaded from: ${N}`);return C}}}if(w){let F=c0(KJ(),".config",w),q=["config",`${w}.config`];if($)q.push(`${$}.config`);if(J)O0.info(`Checking user config directory: ${F}`);for(let R of q)for(let V of f){let L=c0(F,`${R}${V}`),N=await zA(L,W,j);if(N!==null){if(J)O0.success(`Configuration loaded from user config directory: ${L}`);return N}}}if(w){let F=c0(KJ(),".config"),q=[`.${w}.config`];if($)q.push(`.${$}.config`);if(J)O0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of q)for(let V of f){let L=c0(F,`${R}${V}`),N=await zA(L,W,j);if(N!==null){if(J)O0.success(`Configuration loaded from user config directory dotfile: ${L}`);return N}}}if(w){let F=KJ(),q=[`.${w}.config`,`.${w}`];if($)q.push(`.${$}.config`),q.push(`.${$}`);if(J)O0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of q)for(let V of f){let L=c0(F,`${R}${V}`),N=await zA(L,W,j);if(N!==null){if(J)O0.success(`Configuration loaded from user home directory: ${L}`);return N}}}try{let F=c0(Q,"package.json");if(Af(F)){let q=await import(F),R=q[w];if(!R&&$){if(R=q[$],R&&J)O0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)O0.success(`Configuration loaded from package.json: ${R===q[w]?w:$}`);return sJ(W,R,j)}catch(V){if(J)O0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)O0.warn("Failed to load package.json:",F)}if(J)O0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function wE(w,$={}){let Y=RA.cwd();while(Y.includes("storage"))Y=HQ(Y,"..");let A=HQ(Y,w||"");if($?.relative)return J5(RA.cwd(),A);return A}async function $E(){try{let w=await e5({name:"clarity",alias:"logging",defaultConfig:qA,cwd:RA.cwd()});return{...qA,...w||{}}}catch{return qA}}function E0(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YE(){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 Wf{async format(w){let $=await YE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:w1.pid,hostname:$(),environment:w1.env.NODE_ENV||"development",platform:w1.platform,version:w1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:w1.env.NODE_ENV||w1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class SA{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={...uJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Wf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...NA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...NA};return{...NA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await N5(this.config.logDirectory,_Q.F_OK|_Q.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await H5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:kw.from(w);try{if(!AA(this.currentLogFile))await MJ(this.currentLogFile,"",{mode:420});if(X=hQ(this.currentLogFile,"a",420),q5(X,W,{flag:"a"}),OQ(X),X!==void 0)RJ(X),X=void 0;if((await o$(this.currentLogFile)).size===0){if(await MJ(this.currentLogFile,W,{flag:"w",mode:420}),(await o$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{RJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return e$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return e$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return e$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return HJ(16).toString("hex")}generateKey(){return HJ(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=HJ(16),A=K5("aes-256-gcm",$,Y),X=kw.isBuffer(w)?w:kw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=kw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=xQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(kw.from(kw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await o$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await XA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await o$(Y).catch(()=>null))try{if(await DQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await JA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await MJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await o$(Y).catch(()=>null))await DQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await XA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await JA(e$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=SQ(w),A=T5($),X=xQ();await y5(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=hQ(this.currentLogFile,"r+");OQ(w),RJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await XA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await JA(e$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?b.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${b.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=b.underline(b.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(R5($)||$.startsWith("./")||$.startsWith("../"))$=M5($);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,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Tf[w],B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
11
11
|
`);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:b.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
|
|
12
12
|
`;if(j)f+=`${j}
|
|
13
13
|
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!E0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!E0()&&x.stdout.isTTY)x.stdout.write(`
|
|
@@ -28,7 +28,7 @@ import{createRequire as r6}from"node:module";var n6=Object.defineProperty;var l6
|
|
|
28
28
|
`;Y+=`| Variable | Type | Description | Example |
|
|
29
29
|
`,Y+=`|----------|------|-------------|----------|
|
|
30
30
|
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
31
|
-
`;return Y}}function JE(w,$){let Y=Ef("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function ff(w,$,Y={}){return zf(w,$,Y,new WeakMap)}function zf(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Bf(w,$,X,A);if(!Ww($)||!Ww(w))return $;return QE(w,$,Y,A)}function Bf(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return UE(w,$);case"smart":return WE(w,$,A);default:return $}return $}function UE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>iJ(X,A)))Y.push(A);return Y}function WE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Ww($[0])&&Ww(w[0]))return jE(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 jE(w,$,Y){let A=[...$];for(let X of w){if(!Ww(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Ww(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function QE(w,$,Y,A){let X=$;if(Ww(X)&&A.has(X))return A.get(X);let J={...w};if(Ww(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Ww(j)&&Ww(W))J[U]=zf(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Bf(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oJ(w,$,Y="replace"){return ff(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function iJ(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(!iJ(w[Y],$[Y]))return!1;return!0}if(Ww(w)&&Ww($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!iJ(w[X],$[X]))return!1}return!0}return!1}function Ww(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class PA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=X1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!WA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new s1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new s1(w,Error("Configuration must export a valid object"),"unknown");let F={config:oJ($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)X1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?Q$.configLoad(w,Q):Q$.configLoad(w,Error(String(Q)))}};if(U)return e1.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(yJ($,`${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 jf(async()=>{return WA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!WA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=yJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=yJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!WA(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:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await e1.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!I5($))throw new o1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new o1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:qf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class wU{fileLoader=new PA;envProcessor=new ZA;validator=new eJ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Fw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Fw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||O$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(v0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw Q$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?t1(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Fw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Fw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?t1(w,Y,X):Y,j=[v0(r$(),".config",w),v0(r$(),".config"),r$()];for(let W of j){if(X)Fw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Fw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?t1(w,A,J):A;try{let W=v0(Y,"package.json");if(!ZJ(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Fw.success(`Configuration loaded from package.json: ${z}`);return{config:oJ(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Fw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:t1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Q$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return X1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);X1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,v0(w,"config"),v0(w,".config"),$?v0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(v0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[v0(r$(),".config",w),v0(r$(),".config"),r$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function mQ(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 fE(w){return uw.loadConfig({...w,__strictErrorHandling:!0})}async function Gf(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await uw.loadConfig(w);else A=await uw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Fw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await uw.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function zE(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await uw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&mQ(Y)))return(await uw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await uw.loadConfig({...w,cwd:w.cwd||O$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&mQ($)))return(await uw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function BE(w,$,Y="replace"){let A=new PA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function t1(w,$,Y=!1){let A=new ZA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=O$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function GE(w){let $=v0(O$.cwd(),w.configDir),Y=v0(O$.cwd(),w.generatedDir),A=v0(Y,"config-types.ts");if(!ZJ(qQ(A)))$5(qQ(A),{recursive:!0,mode:511});let X=ZJ($)?Y5($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${mE}
|
|
31
|
+
`;return Y}}function JE(w,$){let Y=Ef("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function ff(w,$,Y={}){return zf(w,$,Y,new WeakMap)}function zf(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Bf(w,$,X,A);if(!Ww($)||!Ww(w))return $;return QE(w,$,Y,A)}function Bf(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return UE(w,$);case"smart":return WE(w,$,A);default:return $}return $}function UE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>iJ(X,A)))Y.push(A);return Y}function WE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Ww($[0])&&Ww(w[0]))return jE(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 jE(w,$,Y){let A=[...$];for(let X of w){if(!Ww(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Ww(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function QE(w,$,Y,A){let X=$;if(Ww(X)&&A.has(X))return A.get(X);let J={...w};if(Ww(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Ww(j)&&Ww(W))J[U]=zf(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Bf(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oJ(w,$,Y="replace"){return ff(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function iJ(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(!iJ(w[Y],$[Y]))return!1;return!0}if(Ww(w)&&Ww($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!iJ(w[X],$[X]))return!1}return!0}return!1}function Ww(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class PA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=X1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!WA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new s1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new s1(w,Error("Configuration must export a valid object"),"unknown");let F={config:oJ($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)X1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?Q$.configLoad(w,Q):Q$.configLoad(w,Error(String(Q)))}};if(U)return e1.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(yJ($,`${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 jf(async()=>{return WA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!WA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=yJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=yJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!WA(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:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await e1.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!I5($))throw new o1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new o1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Nf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class wU{fileLoader=new PA;envProcessor=new ZA;validator=new eJ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Fw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Fw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||O$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(v0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw Q$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?t1(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Fw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Fw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?t1(w,Y,X):Y,j=[v0(r$(),".config",w),v0(r$(),".config"),r$()];for(let W of j){if(X)Fw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Fw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?t1(w,A,J):A;try{let W=v0(Y,"package.json");if(!ZJ(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Fw.success(`Configuration loaded from package.json: ${z}`);return{config:oJ(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Fw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:t1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Q$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return X1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);X1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,v0(w,"config"),v0(w,".config"),$?v0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(v0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[v0(r$(),".config",w),v0(r$(),".config"),r$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function mQ(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 fE(w){return uw.loadConfig({...w,__strictErrorHandling:!0})}async function Gf(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await uw.loadConfig(w);else A=await uw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Fw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await uw.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function zE(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await uw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&mQ(Y)))return(await uw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await uw.loadConfig({...w,cwd:w.cwd||O$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&mQ($)))return(await uw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function BE(w,$,Y="replace"){let A=new PA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function t1(w,$,Y=!1){let A=new ZA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=O$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function GE(w){let $=v0(O$.cwd(),w.configDir),Y=v0(O$.cwd(),w.generatedDir),A=v0(Y,"config-types.ts");if(!ZJ(NQ(A)))$5(NQ(A),{recursive:!0,mode:511});let X=ZJ($)?Y5($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${mE}
|
|
32
32
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
33
33
|
`;A5(A,J,{mode:438})}function EE(w){let $=null,Y=null,A=()=>{if(!Y)Y=Gf(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Fw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function KE(w){let $=kQ(L5.cwd(),w?.configDir||"./config");function Y(){if(!C5($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=V5($).filter((W)=>X.has(IJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=IJ(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=IJ(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
|
|
34
34
|
${X.map((Q)=>{let f=kQ($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${f}').default`}).join(`,
|
|
@@ -58,11 +58,11 @@ export type ConfigOf = Config
|
|
|
58
58
|
`;Y+=`| Variable | Type | Description | Example |
|
|
59
59
|
`,Y+=`|----------|------|-------------|----------|
|
|
60
60
|
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
61
|
-
`;return Y}}function eE(w,$,Y={}){return _f(w,$,Y,new WeakMap)}function _f(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Df(w,$,X,A);if(!jw($)||!jw(w))return $;return AK(w,$,Y,A)}function Df(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 wK(w,$);case"smart":return $K(w,$,A);default:return $}return $}function wK(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>lJ(X,A)))Y.push(A);return Y}function $K(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return YK(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 YK(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>jw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function AK(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(jw(j)&&jw(W))J[U]=_f(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Df(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function xf(w,$,Y="replace"){return eE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function lJ(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(!lJ(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(!lJ(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class kf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=HA.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!GA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new DA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new DA(w,Error("Configuration must export a valid object"),"unknown");let F={config:xf($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)HA.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?J1.configLoad(w,Q):J1.configLoad(w,Error(String(Q)))}};if(U)return pJ.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(xJ($,`${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 oE(async()=>{return GA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!GA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=xJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=xJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!GA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class Zf{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await pJ.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!XK($))throw new xA($,[{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 xA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:JK},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function UK(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 Pf{fileLoader=new kf;envProcessor=new YU;validator=new Zf;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Ow.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw Ow.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||kA.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(Uw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw J1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${UK(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?EA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Ow.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Ow.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?EA(w,Y,X):Y,j=[Uw(p$(),".config",w),Uw(p$(),".config"),p$()];for(let W of j){if(X)Ow.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Ow.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?EA(w,A,J):A;try{let W=Uw(Y,"package.json");if(!eG(W))return null;let Q={};try{Q=JSON.parse(w5(W,"utf8"))}catch(B){if(J)Ow.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Ow.success(`Configuration loaded from package.json: ${z}`);return{config:xf(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Ow.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:EA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw J1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return HA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);HA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Uw(w,"config"),Uw(w,".config"),$?Uw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Uw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Uw(p$(),".config",w),Uw(p$(),".config"),p$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function bf(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 kJ.loadConfig(w);else A=await kJ.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)Ow.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await kJ.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}function EA(w,$,Y=!1){let A=new YU,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=kA.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}var HA,pJ,u5,c5=(w)=>w,m5=(w,$)=>{for(var Y in $)u5(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:v5.bind($,Y)})},g5=(w,$)=>()=>(w&&($=w(w=0)),$),Jf,Ef,X1,e1,Kf,FE,TE,gQ,FA,bJ,S0,o,NE,dQ,qE,nQ,HE,RE,SJ,ME,lQ,pQ,OJ,yE,IE,CE,VE,TA,Ff,LE,O0,SE,OE,rQ,NA,uJ,K0,b,hE,tQ,_E,aQ,DE,xE,hJ,kE,sQ,oQ,ZE,_J,PE,iE,bE,uE,cE,qA,Tf,vE,mE="0.15.6",o0,OA,s1,cJ,vJ,hA,mJ,gJ,o1,dJ,nJ,Q$,Nf,qf,Fw,uw,Hf,Rf,gE,nE,Mf,_A,oy,y0,v,ey,pE,w4,rE,$4,Y4,eQ,A4,tE,aE,X4,wf,J4,U4,W4,j4,Q4,DJ,sE,f4,Tw,If,DA,Cf,Vf,$U,Lf,Sf,xA,Of,hf,J1,JK,Ow,kJ,K4,F4;var uf=s(()=>{HA=new $f,pJ=new Yf,u5=Object.defineProperty;Jf={};m5(Jf,{withErrorRecovery:()=>jf,tryLoadConfig:()=>BE,loadConfigWithResult:()=>fE,loadConfig:()=>Gf,isRetryableError:()=>XE,isConfigNotFoundError:()=>AE,isBunfigError:()=>Qf,globalPerformanceMonitor:()=>e1,globalCache:()=>X1,getEnvOrDefault:()=>JE,generateConfigTypes:()=>GE,defaultGeneratedDir:()=>Rf,defaultConfigDir:()=>Hf,deepMergeWithArrayStrategy:()=>oJ,deepMerge:()=>ff,createLibraryConfig:()=>EE,config:()=>zE,bunfigPlugin:()=>KE,applyEnvVarsToConfig:()=>t1,TypeGenerationError:()=>gJ,SchemaValidationError:()=>o1,PluginError:()=>nJ,PerformanceMonitor:()=>tJ,FileSystemError:()=>mJ,ErrorFactory:()=>Q$,EnvVarError:()=>hA,EnvProcessor:()=>ZA,ConfigValidator:()=>eJ,ConfigValidationError:()=>cJ,ConfigNotFoundError:()=>OA,ConfigMergeError:()=>vJ,ConfigLoader:()=>wU,ConfigLoadError:()=>s1,ConfigFileLoader:()=>PA,ConfigCache:()=>rJ,CacheUtils:()=>Kf,BunfigError:()=>o0,BrowserConfigError:()=>dJ,ArrayMergeStrategies:()=>Nf});gE=g5(async()=>{Ef=import.meta.require,X1=new rJ,e1=new tJ,Kf={createKey:d5,isEquivalent:n5,estimateMemoryUsage:l5},FE=yA(PJ.cwd(),"config"),TE=yA(PJ.cwd(),"src/generated"),gQ=MA.env.CLARITY_LOG_DIR||U5(t5(),"logs"),FA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},bJ=await a5(),S0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=S0,NE=S0.red,dQ=S0.green,qE=S0.yellow,nQ=S0.blue,HE=S0.magenta,RE=S0.cyan,SJ=S0.white,ME=S0.gray,lQ=S0.bgRed,pQ=S0.bgYellow,OJ=S0.bold,yE=S0.dim,IE=S0.italic,CE=S0.underline,VE=S0.reset,TA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ff={debug:"\uD83D\uDD0D",info:nQ("ℹ"),success:dQ("✓"),warning:pQ(SJ(OJ(" WARN "))),error:lQ(SJ(OJ(" ERROR ")))},LE=new VA("stacks"),O0=new VA("bunfig",{showTags:!0}),SE=c0(a1.cwd(),"config"),OE=c0(a1.cwd(),"src/generated"),rQ=RA.env.CLARITY_LOG_DIR||X5(wE(),"logs"),NA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uJ=await $E(),K0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=K0,hE=K0.red,tQ=K0.green,_E=K0.yellow,aQ=K0.blue,DE=K0.magenta,xE=K0.cyan,hJ=K0.white,kE=K0.gray,sQ=K0.bgRed,oQ=K0.bgYellow,ZE=K0.bgGray,_J=K0.bold,PE=K0.dim,iE=K0.italic,bE=K0.underline,uE=K0.strikethrough,cE=K0.reset,qA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tf={debug:"\uD83D\uDD0D",info:aQ("ℹ"),success:tQ("✓"),warning:oQ(hJ(_J(" WARN "))),error:sQ(hJ(_J(" ERROR ")))},vE=new SA("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}${$}`}},OA=class extends o0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},s1=class extends o0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},cJ=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},vJ=class extends o0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},hA=class extends o0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},mJ=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}},gJ=class extends o0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},o1=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},dJ=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})}},nJ=class extends o0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Q$={configNotFound(w,$,Y){return new OA(w,$,Y)},configLoad(w,$,Y){return new s1(w,$,Y)},configValidation(w,$,Y){return new cJ(w,$,Y)},configMerge(w,$,Y,A){return new vJ(w,$,Y,A)},envVar(w,$,Y,A){return new hA(w,$,Y,A)},fileSystem(w,$,Y){return new mJ(w,$,Y)},typeGeneration(w,$,Y){return new gJ(w,$,Y)},schemaValidation(w,$,Y){return new o1(w,$,Y)},browserConfig(w,$,Y,A){return new dJ(w,$,Y,A)},plugin(w,$,Y){return new nJ(w,$,Y)}},Nf={replace:"replace",concat:"concat",smart:"smart"},qf=/^https?:\/\//,Fw=new SA("bunfig",{showTags:!0}),uw=new wU,Hf=v0(O$.cwd(),"config"),Rf=v0(O$.cwd(),"src/generated")});nE=IA.env.CLARITY_LOG_DIR||S5(dE(),"logs"),Mf={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},_A={...Mf},oy=(async()=>{try{let{loadConfig:w}=await gE().then(()=>Jf),$=await w({name:"clarity",alias:"logging",defaultConfig:Mf,cwd:IA.cwd()});if($)Object.assign(_A,$)}catch{}return _A})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=y0,ey=y0.red,pE=y0.green,w4=y0.yellow,rE=y0.blue,$4=y0.magenta,Y4=y0.cyan,eQ=y0.white,A4=y0.gray,tE=y0.bgRed,aE=y0.bgYellow,X4=y0.bgGray,wf=y0.bold,J4=y0.dim,U4=y0.italic,W4=y0.underline,j4=y0.strikethrough,Q4=y0.reset,DJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sE={debug:"\uD83D\uDD0D",info:rE("ℹ"),success:pE("✓"),warning:aE(eQ(wf(" WARN "))),error:tE(eQ(wf(" ERROR ")))};f4=new iA("stacks");Tw=class Tw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};If=class If extends Tw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};DA=class DA extends Tw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};Cf=class Cf extends Tw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Vf=class Vf extends Tw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};$U=class $U extends Tw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};Lf=class Lf extends Tw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Sf=class Sf extends Tw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};xA=class xA extends Tw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Of=class Of extends Tw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};hf=class hf extends Tw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};J1={configNotFound(w,$,Y){return new If(w,$,Y)},configLoad(w,$,Y){return new DA(w,$,Y)},configValidation(w,$,Y){return new Cf(w,$,Y)},configMerge(w,$,Y,A){return new Vf(w,$,Y,A)},envVar(w,$,Y,A){return new $U(w,$,Y,A)},fileSystem(w,$,Y){return new Lf(w,$,Y)},typeGeneration(w,$,Y){return new Sf(w,$,Y)},schemaValidation(w,$,Y){return new xA(w,$,Y)},browserConfig(w,$,Y,A){return new Of(w,$,Y,A)},plugin(w,$,Y){return new hf(w,$,Y)}};JK=/^https?:\/\//;Ow=new iA("bunfig",{showTags:!0});kJ=new Pf;K4=Uw(kA.cwd(),"config"),F4=Uw(kA.cwd(),"src/generated")});import{homedir as AU}from"node:os";import{join as XU,resolve as WK}from"node:path";async function vf(){if(!JU)JU=await bf({name:"rpx",cwd:WK(__dirname,".."),defaultConfig:cf});return JU}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",cf,JU=null,cw;var bA=s(()=>{uf();cf={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:XU(AU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:XU(AU(),".stacks","ssl","stacks.localhost.crt"),keyPath:XU(AU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};cw=cf});function U1(w){return w.startsWith("*.")}function wY(w,$){if(!U1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function mf(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!U1(J))continue;if(wY($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}import{existsSync as jK,readdirSync as QK,readFileSync as fK,statSync as zK}from"node:fs";import{homedir as df}from"node:os";import{isAbsolute as BK,join as W1}from"node:path";function WU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return W1($,w.slice(2));return w}function EK(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function uA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function KK(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function FK(w,$){let Y=$.readText(W1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(W1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function TK(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 NK(w,$){let Y=FK(w,$);if(Y?.command)return TK(Y);let A=$.fileExists(W1(w,"buddy")),X=$.readText(W1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function jU(w,$={}){let Y={dirExists:$.dirExists??UU.dirExists,fileExists:$.fileExists??UU.fileExists,readText:$.readText??UU.readText},A=$.detect??NK,X=$.homeDir??df(),J=w.tlds??lf,U=(w.roots??nf).map((B)=>WU(B,X)),j=w.idleTimeoutMs??GK,W=new Map;for(let B of w.sites??[])W.set(B.to,B);let Q=(B)=>B.idleTimeoutMs??j;function f(B){let G=mf(W,B);if(!G)return null;let T=BK(G.dir)?G.dir:WU(G.dir,X),K=G.selfRegisters??!1,F=G.routes??[];if(!K&&F.length===0)F=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let N=gf({...G.env??{}},void 0,B);return{host:B,id:uA(B),dir:T,command:G.command,env:N,routes:F,selfRegisters:K,idleTimeoutMs:Q(G),source:"config"}}function z(B){let G=KK(B,J);if(!G)return null;for(let T of U){let K=W1(T,G);if(!Y.dirExists(K))continue;let F=A(K,Y);if(!F)continue;let N=F.selfRegisters??!1;return{host:B,id:uA(B),dir:K,command:F.command,env:gf({...F.env??{}},F.urlEnv,B),routes:N?[]:F.routes??[],selfRegisters:N,idleTimeoutMs:j,source:"discovered"}}return null}return{resolve(B){let G=EK(B);if(!G)return null;return f(G)??z(G)}}}function qK(w){try{return QK(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function pf(w,$={}){let Y=$.homeDir??df(),A=w.tlds??lf,X=(w.roots??nf).map((z)=>WU(z,Y)),J=$.readdir??qK,U=jU(w,$),j=[],W=new Set,Q=(z)=>{if(z&&!W.has(z.host))W.add(z.host),j.push(z)};for(let z of w.sites??[])if(!z.to.includes("*"))Q(U.resolve(z.to));let f=A[0]??"localhost";for(let z of X)for(let B of J(z))Q(U.resolve(`${B}.${f}`));return j}function gf(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var nf,lf,GK=1800000,UU;var QU=s(()=>{nf=["~/Code"],lf=["localhost","test"],UU={dirExists:(w)=>{try{return zK(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return jK(w)}catch{return!1}},readText:(w)=>{try{return fK(w,"utf8")}catch{return null}}}});var H;var _$=s(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as HK}from"node:module";import{Resolver as fU}from"node:dns/promises";import{createHash as MK,sign as yK}from"node:crypto";import{createHash as IK}from"node:crypto";import{sign as CK}from"node:crypto";import{generateKeyPairSync as ez,X509Certificate as kK}from"node:crypto";import zU from"node:os";import BU from"node:path";import{existsSync as tf,statSync as af}from"fs";import{existsSync as PK,mkdirSync as u4,readdirSync as c4,readFileSync as iK,writeFileSync as v4}from"fs";import{homedir as j1}from"os";import{dirname as d4,resolve as fw}from"path";import VX from"process";import{existsSync as sf,statSync as of}from"fs";import{existsSync as PU,mkdirSync as bK,readdirSync as uK,writeFileSync as cK}from"fs";import{homedir as Q1}from"os";import{dirname as ef,resolve as g0}from"path";import x$ from"process";import{join as vK,relative as mK,resolve as wz}from"path";import QX from"process";import{existsSync as wB,mkdirSync as wI,readdirSync as $I,writeFileSync as YI}from"fs";import{homedir as GU}from"os";import{dirname as JI,resolve as m0}from"path";import JY from"process";import{join as gK,relative as dK,resolve as $z}from"path";import fX from"process";import{existsSync as $B,mkdirSync as fI,readdirSync as zI,writeFileSync as BI}from"fs";import{dirname as EI,resolve as zX}from"path";import iU from"process";import{Buffer as f$}from"buffer";import{createCipheriv as nK,createDecipheriv as lK,randomBytes as EU}from"crypto";import{closeSync as KU,createReadStream as Yz,createWriteStream as pK,existsSync as FU,fsyncSync as Az,openSync as Xz,writeFileSync as rK}from"fs";import{access as tK,constants as Jz,mkdir as aK,readdir as cA,rename as Uz,stat as f1,unlink as vA,writeFile as TU}from"fs/promises";import{join as z1}from"path";import h0 from"process";import{pipeline as sK}from"stream/promises";import{createGzip as Wz}from"zlib";import B1 from"process";import dw from"process";import{Buffer as vw}from"buffer";import{createCipheriv as oK,createDecipheriv as eK,randomBytes as NU}from"crypto";import{closeSync as qU,createReadStream as jz,createWriteStream as wF,existsSync as mA,fsyncSync as Qz,openSync as fz,writeFileSync as $F}from"fs";import{access as YF,constants as zz,mkdir as AF,readdir as gA,rename as Bz,stat as G1,unlink as dA,writeFile as HU}from"fs/promises";import{isAbsolute as XF,join as E1,resolve as JF}from"path";import p from"process";import{pipeline as UF}from"stream/promises";import{createGzip as Gz}from"zlib";import K1 from"process";import nw from"process";import nA from"process";import{existsSync as lA}from"fs";import{resolve as RU}from"path";import{existsSync as WF}from"fs";import{existsSync as jF,readdirSync as QF}from"fs";import{extname as MU,resolve as Ez}from"path";import fF from"process";import{join as zF,relative as BF,resolve as Kz}from"path";import BX from"process";import{Buffer as mw}from"buffer";import{createCipheriv as GF,createDecipheriv as EF,randomBytes as yU}from"crypto";import{closeSync as IU,createReadStream as Fz,createWriteStream as KF,existsSync as pA,fsyncSync as Tz,openSync as Nz,writeFileSync as FF}from"fs";import{access as TF,constants as qz,mkdir as NF,readdir as rA,rename as Hz,stat as F1,unlink as tA,writeFile as CU}from"fs/promises";import{isAbsolute as qF,join as T1,resolve as HF}from"path";import r from"process";import{pipeline as RF}from"stream/promises";import{createGzip as Rz}from"zlib";import N1 from"process";import lw from"process";import aA from"process";import{existsSync as sA}from"fs";import{resolve as VU}from"path";import{existsSync as MF}from"fs";import{exec as dT}from"node:child_process";import rU from"node:fs";import nT from"node:os";import Nw from"node:path";import iB from"node:process";import{promisify as lT}from"node:util";import M1 from"node:crypto";import pw from"node:fs";import sU from"node:path";import K7 from"node:crypto";import{execSync as N7}from"node:child_process";import IX 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 cz(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let Q=new fU,f=await Q.resolveNs(J),z=(await Promise.all(f.map((B)=>Q.resolve4(B).catch(()=>[])))).flat();if(z.length>0)U=new fU,U.setServers(z)}catch{}let j=Date.now()+A,W=U??new fU;for(;;){try{if((await W.resolveTxt(w)).some((Q)=>Q.join("")===$))return!0}catch{}if(Date.now()>=j)return!1;await new Promise((Q)=>setTimeout(Q,X))}}class XY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(XY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+XY.PATH_PREFIX.length);return this.get(Y)}}function $X(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function DU(w){return Buffer.from(w,"base64url")}function vz(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 mz(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return MK("sha256").update($).digest("base64url")}function gz(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=$X(JSON.stringify($)),J=Y===""?"":$X(JSON.stringify(Y)),U=`${X}.${J}`,j=yK("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:$X(j)}}class jX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=vz(w.accountPublicKey),this.thumbprint=mz(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??uz}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=gz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await wX($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),j=U.headers.get("replay-nonce");if(j)this.nonce=j;let W=U.headers.get("content-type")??"",Q;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))Q=await U.text();else{let f=await U.text();Q=f?JSON.parse(f):{}}if(U.status>=400){let f=Q??{};throw new WX(`ACME request to ${$} failed (HTTP ${U.status}): ${f.type??""} ${f.detail??""}`.trim(),f,U.status)}return{status:U.status,headers:U.headers,body:Q,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return IK("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((j)=>j.status==="invalid");throw new WX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await rf(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 rf(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 lz(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
|
|
61
|
+
`;return Y}}function eE(w,$,Y={}){return _f(w,$,Y,new WeakMap)}function _f(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Df(w,$,X,A);if(!jw($)||!jw(w))return $;return AK(w,$,Y,A)}function Df(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 wK(w,$);case"smart":return $K(w,$,A);default:return $}return $}function wK(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>lJ(X,A)))Y.push(A);return Y}function $K(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return YK(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 YK(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>jw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function AK(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(jw(j)&&jw(W))J[U]=_f(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Df(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function xf(w,$,Y="replace"){return eE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function lJ(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(!lJ(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(!lJ(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class kf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=HA.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!GA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new DA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new DA(w,Error("Configuration must export a valid object"),"unknown");let F={config:xf($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)HA.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?J1.configLoad(w,Q):J1.configLoad(w,Error(String(Q)))}};if(U)return pJ.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(xJ($,`${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 oE(async()=>{return GA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!GA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=xJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=xJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!GA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class Zf{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await pJ.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!XK($))throw new xA($,[{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 xA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:JK},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function UK(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 Pf{fileLoader=new kf;envProcessor=new YU;validator=new Zf;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Ow.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw Ow.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||kA.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(Uw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw J1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${UK(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?EA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Ow.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Ow.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?EA(w,Y,X):Y,j=[Uw(p$(),".config",w),Uw(p$(),".config"),p$()];for(let W of j){if(X)Ow.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Ow.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?EA(w,A,J):A;try{let W=Uw(Y,"package.json");if(!eG(W))return null;let Q={};try{Q=JSON.parse(w5(W,"utf8"))}catch(B){if(J)Ow.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Ow.success(`Configuration loaded from package.json: ${z}`);return{config:xf(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Ow.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:EA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw J1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return HA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);HA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Uw(w,"config"),Uw(w,".config"),$?Uw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Uw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Uw(p$(),".config",w),Uw(p$(),".config"),p$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function bf(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 kJ.loadConfig(w);else A=await kJ.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)Ow.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await kJ.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}function EA(w,$,Y=!1){let A=new YU,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=kA.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}var HA,pJ,u5,c5=(w)=>w,m5=(w,$)=>{for(var Y in $)u5(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:v5.bind($,Y)})},g5=(w,$)=>()=>(w&&($=w(w=0)),$),Jf,Ef,X1,e1,Kf,FE,TE,gQ,FA,bJ,S0,o,qE,dQ,NE,nQ,HE,RE,SJ,ME,lQ,pQ,OJ,yE,IE,CE,VE,TA,Ff,LE,O0,SE,OE,rQ,qA,uJ,K0,b,hE,tQ,_E,aQ,DE,xE,hJ,kE,sQ,oQ,ZE,_J,PE,iE,bE,uE,cE,NA,Tf,vE,mE="0.15.6",o0,OA,s1,cJ,vJ,hA,mJ,gJ,o1,dJ,nJ,Q$,qf,Nf,Fw,uw,Hf,Rf,gE,nE,Mf,_A,oy,y0,v,ey,pE,w4,rE,$4,Y4,eQ,A4,tE,aE,X4,wf,J4,U4,W4,j4,Q4,DJ,sE,f4,Tw,If,DA,Cf,Vf,$U,Lf,Sf,xA,Of,hf,J1,JK,Ow,kJ,K4,F4;var uf=s(()=>{HA=new $f,pJ=new Yf,u5=Object.defineProperty;Jf={};m5(Jf,{withErrorRecovery:()=>jf,tryLoadConfig:()=>BE,loadConfigWithResult:()=>fE,loadConfig:()=>Gf,isRetryableError:()=>XE,isConfigNotFoundError:()=>AE,isBunfigError:()=>Qf,globalPerformanceMonitor:()=>e1,globalCache:()=>X1,getEnvOrDefault:()=>JE,generateConfigTypes:()=>GE,defaultGeneratedDir:()=>Rf,defaultConfigDir:()=>Hf,deepMergeWithArrayStrategy:()=>oJ,deepMerge:()=>ff,createLibraryConfig:()=>EE,config:()=>zE,bunfigPlugin:()=>KE,applyEnvVarsToConfig:()=>t1,TypeGenerationError:()=>gJ,SchemaValidationError:()=>o1,PluginError:()=>nJ,PerformanceMonitor:()=>tJ,FileSystemError:()=>mJ,ErrorFactory:()=>Q$,EnvVarError:()=>hA,EnvProcessor:()=>ZA,ConfigValidator:()=>eJ,ConfigValidationError:()=>cJ,ConfigNotFoundError:()=>OA,ConfigMergeError:()=>vJ,ConfigLoader:()=>wU,ConfigLoadError:()=>s1,ConfigFileLoader:()=>PA,ConfigCache:()=>rJ,CacheUtils:()=>Kf,BunfigError:()=>o0,BrowserConfigError:()=>dJ,ArrayMergeStrategies:()=>qf});gE=g5(async()=>{Ef=import.meta.require,X1=new rJ,e1=new tJ,Kf={createKey:d5,isEquivalent:n5,estimateMemoryUsage:l5},FE=yA(PJ.cwd(),"config"),TE=yA(PJ.cwd(),"src/generated"),gQ=MA.env.CLARITY_LOG_DIR||U5(t5(),"logs"),FA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},bJ=await a5(),S0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=S0,qE=S0.red,dQ=S0.green,NE=S0.yellow,nQ=S0.blue,HE=S0.magenta,RE=S0.cyan,SJ=S0.white,ME=S0.gray,lQ=S0.bgRed,pQ=S0.bgYellow,OJ=S0.bold,yE=S0.dim,IE=S0.italic,CE=S0.underline,VE=S0.reset,TA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ff={debug:"\uD83D\uDD0D",info:nQ("ℹ"),success:dQ("✓"),warning:pQ(SJ(OJ(" WARN "))),error:lQ(SJ(OJ(" ERROR ")))},LE=new VA("stacks"),O0=new VA("bunfig",{showTags:!0}),SE=c0(a1.cwd(),"config"),OE=c0(a1.cwd(),"src/generated"),rQ=RA.env.CLARITY_LOG_DIR||X5(wE(),"logs"),qA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uJ=await $E(),K0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=K0,hE=K0.red,tQ=K0.green,_E=K0.yellow,aQ=K0.blue,DE=K0.magenta,xE=K0.cyan,hJ=K0.white,kE=K0.gray,sQ=K0.bgRed,oQ=K0.bgYellow,ZE=K0.bgGray,_J=K0.bold,PE=K0.dim,iE=K0.italic,bE=K0.underline,uE=K0.strikethrough,cE=K0.reset,NA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tf={debug:"\uD83D\uDD0D",info:aQ("ℹ"),success:tQ("✓"),warning:oQ(hJ(_J(" WARN "))),error:sQ(hJ(_J(" ERROR ")))},vE=new SA("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}${$}`}},OA=class extends o0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},s1=class extends o0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},cJ=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},vJ=class extends o0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},hA=class extends o0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},mJ=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}},gJ=class extends o0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},o1=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},dJ=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})}},nJ=class extends o0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Q$={configNotFound(w,$,Y){return new OA(w,$,Y)},configLoad(w,$,Y){return new s1(w,$,Y)},configValidation(w,$,Y){return new cJ(w,$,Y)},configMerge(w,$,Y,A){return new vJ(w,$,Y,A)},envVar(w,$,Y,A){return new hA(w,$,Y,A)},fileSystem(w,$,Y){return new mJ(w,$,Y)},typeGeneration(w,$,Y){return new gJ(w,$,Y)},schemaValidation(w,$,Y){return new o1(w,$,Y)},browserConfig(w,$,Y,A){return new dJ(w,$,Y,A)},plugin(w,$,Y){return new nJ(w,$,Y)}},qf={replace:"replace",concat:"concat",smart:"smart"},Nf=/^https?:\/\//,Fw=new SA("bunfig",{showTags:!0}),uw=new wU,Hf=v0(O$.cwd(),"config"),Rf=v0(O$.cwd(),"src/generated")});nE=IA.env.CLARITY_LOG_DIR||S5(dE(),"logs"),Mf={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},_A={...Mf},oy=(async()=>{try{let{loadConfig:w}=await gE().then(()=>Jf),$=await w({name:"clarity",alias:"logging",defaultConfig:Mf,cwd:IA.cwd()});if($)Object.assign(_A,$)}catch{}return _A})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=y0,ey=y0.red,pE=y0.green,w4=y0.yellow,rE=y0.blue,$4=y0.magenta,Y4=y0.cyan,eQ=y0.white,A4=y0.gray,tE=y0.bgRed,aE=y0.bgYellow,X4=y0.bgGray,wf=y0.bold,J4=y0.dim,U4=y0.italic,W4=y0.underline,j4=y0.strikethrough,Q4=y0.reset,DJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sE={debug:"\uD83D\uDD0D",info:rE("ℹ"),success:pE("✓"),warning:aE(eQ(wf(" WARN "))),error:tE(eQ(wf(" ERROR ")))};f4=new iA("stacks");Tw=class Tw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};If=class If extends Tw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};DA=class DA extends Tw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};Cf=class Cf extends Tw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Vf=class Vf extends Tw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};$U=class $U extends Tw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};Lf=class Lf extends Tw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Sf=class Sf extends Tw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};xA=class xA extends Tw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Of=class Of extends Tw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};hf=class hf extends Tw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};J1={configNotFound(w,$,Y){return new If(w,$,Y)},configLoad(w,$,Y){return new DA(w,$,Y)},configValidation(w,$,Y){return new Cf(w,$,Y)},configMerge(w,$,Y,A){return new Vf(w,$,Y,A)},envVar(w,$,Y,A){return new $U(w,$,Y,A)},fileSystem(w,$,Y){return new Lf(w,$,Y)},typeGeneration(w,$,Y){return new Sf(w,$,Y)},schemaValidation(w,$,Y){return new xA(w,$,Y)},browserConfig(w,$,Y,A){return new Of(w,$,Y,A)},plugin(w,$,Y){return new hf(w,$,Y)}};JK=/^https?:\/\//;Ow=new iA("bunfig",{showTags:!0});kJ=new Pf;K4=Uw(kA.cwd(),"config"),F4=Uw(kA.cwd(),"src/generated")});import{homedir as AU}from"node:os";import{join as XU,resolve as WK}from"node:path";async function vf(){if(!JU)JU=await bf({name:"rpx",cwd:WK(__dirname,".."),defaultConfig:cf});return JU}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",cf,JU=null,cw;var bA=s(()=>{uf();cf={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:XU(AU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:XU(AU(),".stacks","ssl","stacks.localhost.crt"),keyPath:XU(AU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};cw=cf});function U1(w){return w.startsWith("*.")}function wY(w,$){if(!U1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function mf(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!U1(J))continue;if(wY($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}import{existsSync as jK,readdirSync as QK,readFileSync as fK,statSync as zK}from"node:fs";import{homedir as df}from"node:os";import{isAbsolute as BK,join as W1}from"node:path";function WU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return W1($,w.slice(2));return w}function EK(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function uA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function KK(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function FK(w,$){let Y=$.readText(W1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(W1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function TK(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 qK(w,$){let Y=FK(w,$);if(Y?.command)return TK(Y);let A=$.fileExists(W1(w,"buddy")),X=$.readText(W1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function jU(w,$={}){let Y={dirExists:$.dirExists??UU.dirExists,fileExists:$.fileExists??UU.fileExists,readText:$.readText??UU.readText},A=$.detect??qK,X=$.homeDir??df(),J=w.tlds??lf,U=(w.roots??nf).map((B)=>WU(B,X)),j=w.idleTimeoutMs??GK,W=new Map;for(let B of w.sites??[])W.set(B.to,B);let Q=(B)=>B.idleTimeoutMs??j;function f(B){let G=mf(W,B);if(!G)return null;let T=BK(G.dir)?G.dir:WU(G.dir,X),K=G.selfRegisters??!1,F=G.routes??[];if(!K&&F.length===0)F=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let q=gf({...G.env??{}},void 0,B);return{host:B,id:uA(B),dir:T,command:G.command,env:q,routes:F,selfRegisters:K,idleTimeoutMs:Q(G),source:"config"}}function z(B){let G=KK(B,J);if(!G)return null;for(let T of U){let K=W1(T,G);if(!Y.dirExists(K))continue;let F=A(K,Y);if(!F)continue;let q=F.selfRegisters??!1;return{host:B,id:uA(B),dir:K,command:F.command,env:gf({...F.env??{}},F.urlEnv,B),routes:q?[]:F.routes??[],selfRegisters:q,idleTimeoutMs:j,source:"discovered"}}return null}return{resolve(B){let G=EK(B);if(!G)return null;return f(G)??z(G)}}}function NK(w){try{return QK(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function pf(w,$={}){let Y=$.homeDir??df(),A=w.tlds??lf,X=(w.roots??nf).map((z)=>WU(z,Y)),J=$.readdir??NK,U=jU(w,$),j=[],W=new Set,Q=(z)=>{if(z&&!W.has(z.host))W.add(z.host),j.push(z)};for(let z of w.sites??[])if(!z.to.includes("*"))Q(U.resolve(z.to));let f=A[0]??"localhost";for(let z of X)for(let B of J(z))Q(U.resolve(`${B}.${f}`));return j}function gf(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var nf,lf,GK=1800000,UU;var QU=s(()=>{nf=["~/Code"],lf=["localhost","test"],UU={dirExists:(w)=>{try{return zK(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return jK(w)}catch{return!1}},readText:(w)=>{try{return fK(w,"utf8")}catch{return null}}}});var H;var _$=s(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as HK}from"node:module";import{Resolver as fU}from"node:dns/promises";import{createHash as MK,sign as yK}from"node:crypto";import{createHash as IK}from"node:crypto";import{sign as CK}from"node:crypto";import{generateKeyPairSync as ez,X509Certificate as kK}from"node:crypto";import zU from"node:os";import BU from"node:path";import{existsSync as tf,statSync as af}from"fs";import{existsSync as PK,mkdirSync as u4,readdirSync as c4,readFileSync as iK,writeFileSync as v4}from"fs";import{homedir as j1}from"os";import{dirname as d4,resolve as fw}from"path";import VX from"process";import{existsSync as sf,statSync as of}from"fs";import{existsSync as PU,mkdirSync as bK,readdirSync as uK,writeFileSync as cK}from"fs";import{homedir as Q1}from"os";import{dirname as ef,resolve as g0}from"path";import x$ from"process";import{join as vK,relative as mK,resolve as wz}from"path";import QX from"process";import{existsSync as wB,mkdirSync as wI,readdirSync as $I,writeFileSync as YI}from"fs";import{homedir as GU}from"os";import{dirname as JI,resolve as m0}from"path";import JY from"process";import{join as gK,relative as dK,resolve as $z}from"path";import fX from"process";import{existsSync as $B,mkdirSync as fI,readdirSync as zI,writeFileSync as BI}from"fs";import{dirname as EI,resolve as zX}from"path";import iU from"process";import{Buffer as f$}from"buffer";import{createCipheriv as nK,createDecipheriv as lK,randomBytes as EU}from"crypto";import{closeSync as KU,createReadStream as Yz,createWriteStream as pK,existsSync as FU,fsyncSync as Az,openSync as Xz,writeFileSync as rK}from"fs";import{access as tK,constants as Jz,mkdir as aK,readdir as cA,rename as Uz,stat as f1,unlink as vA,writeFile as TU}from"fs/promises";import{join as z1}from"path";import h0 from"process";import{pipeline as sK}from"stream/promises";import{createGzip as Wz}from"zlib";import B1 from"process";import dw from"process";import{Buffer as vw}from"buffer";import{createCipheriv as oK,createDecipheriv as eK,randomBytes as qU}from"crypto";import{closeSync as NU,createReadStream as jz,createWriteStream as wF,existsSync as mA,fsyncSync as Qz,openSync as fz,writeFileSync as $F}from"fs";import{access as YF,constants as zz,mkdir as AF,readdir as gA,rename as Bz,stat as G1,unlink as dA,writeFile as HU}from"fs/promises";import{isAbsolute as XF,join as E1,resolve as JF}from"path";import p from"process";import{pipeline as UF}from"stream/promises";import{createGzip as Gz}from"zlib";import K1 from"process";import nw from"process";import nA from"process";import{existsSync as lA}from"fs";import{resolve as RU}from"path";import{existsSync as WF}from"fs";import{existsSync as jF,readdirSync as QF}from"fs";import{extname as MU,resolve as Ez}from"path";import fF from"process";import{join as zF,relative as BF,resolve as Kz}from"path";import BX from"process";import{Buffer as mw}from"buffer";import{createCipheriv as GF,createDecipheriv as EF,randomBytes as yU}from"crypto";import{closeSync as IU,createReadStream as Fz,createWriteStream as KF,existsSync as pA,fsyncSync as Tz,openSync as qz,writeFileSync as FF}from"fs";import{access as TF,constants as Nz,mkdir as qF,readdir as rA,rename as Hz,stat as F1,unlink as tA,writeFile as CU}from"fs/promises";import{isAbsolute as NF,join as T1,resolve as HF}from"path";import r from"process";import{pipeline as RF}from"stream/promises";import{createGzip as Rz}from"zlib";import q1 from"process";import lw from"process";import aA from"process";import{existsSync as sA}from"fs";import{resolve as VU}from"path";import{existsSync as MF}from"fs";import{exec as dT}from"node:child_process";import rU from"node:fs";import nT from"node:os";import qw from"node:path";import iB from"node:process";import{promisify as lT}from"node:util";import M1 from"node:crypto";import pw from"node:fs";import sU from"node:path";import K7 from"node:crypto";import{execSync as q7}from"node:child_process";import IX 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 cz(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let Q=new fU,f=await Q.resolveNs(J),z=(await Promise.all(f.map((B)=>Q.resolve4(B).catch(()=>[])))).flat();if(z.length>0)U=new fU,U.setServers(z)}catch{}let j=Date.now()+A,W=U??new fU;for(;;){try{if((await W.resolveTxt(w)).some((Q)=>Q.join("")===$))return!0}catch{}if(Date.now()>=j)return!1;await new Promise((Q)=>setTimeout(Q,X))}}class XY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(XY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+XY.PATH_PREFIX.length);return this.get(Y)}}function $X(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function DU(w){return Buffer.from(w,"base64url")}function vz(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 mz(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return MK("sha256").update($).digest("base64url")}function gz(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=$X(JSON.stringify($)),J=Y===""?"":$X(JSON.stringify(Y)),U=`${X}.${J}`,j=yK("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:$X(j)}}class jX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=vz(w.accountPublicKey),this.thumbprint=mz(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??uz}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=gz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await wX($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),j=U.headers.get("replay-nonce");if(j)this.nonce=j;let W=U.headers.get("content-type")??"",Q;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))Q=await U.text();else{let f=await U.text();Q=f?JSON.parse(f):{}}if(U.status>=400){let f=Q??{};throw new WX(`ACME request to ${$} failed (HTTP ${U.status}): ${f.type??""} ${f.detail??""}`.trim(),f,U.status)}return{status:U.status,headers:U.headers,body:Q,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return IK("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((j)=>j.status==="invalid");throw new WX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await rf(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 rf(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 lz(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
|
|
62
62
|
`,chainPem:""};let A=`${Y.trim()}
|
|
63
63
|
`,X=$.slice(1).map((J)=>J.trim()).join(`
|
|
64
64
|
`);return{certPem:A,chainPem:X?`${X}
|
|
65
|
-
`:""}}function pz(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function rf(w){return new Promise(($)=>setTimeout($,w))}function VK(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function G$(w,$){return Buffer.concat([Buffer.from([w]),VK($.length),$])}function rz(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return G$(2,$)}function D$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return G$(6,Buffer.from(Y))}function Qw(...w){return G$(48,Buffer.concat(w))}function xU(...w){return G$(49,Buffer.concat(w))}function kU(w){return G$(3,Buffer.concat([Buffer.from([0]),w]))}function tz(w){return G$(4,w)}function az(w){return G$(12,Buffer.from(w,"utf8"))}function ZU(w,$,Y){let A=128|(Y?32:0)|w;return G$(A,$)}function xK(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=DU($.x),A=DU($.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function sz(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(xU(Qw(D$(hK),az($[0])))),J=Qw(Qw(D$(LK),D$(SK)),kU(xK(Y))),U=$.map((K)=>ZU(2,Buffer.from(K,"ascii"),!1)),j=Qw(...U),W=Qw(D$(DK),tz(j)),Q=Qw(W),f=Qw(D$(_K),xU(Q)),z=ZU(0,f,!0),B=Qw(rz(0),X,J,z),G=CK("sha256",B,A),T=Qw(D$(OK));return Qw(B,T,kU(G))}function oz(w){return sz(w).toString("base64url")}function ZK(w){if(w){let{createPrivateKey:X,createPublicKey:J}=RK("node:crypto"),U=X(w),j=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:j,pem:w}}let{privateKey:$,publicKey:Y}=ez("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function oU(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?nz:dz),X=ZK(w.accountKeyPem),J=new jX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:j}=await J.newOrder($),W=w.http01Store??CX,Q=[],f=[];try{for(let q of U.authorizations){let C=await J.getAuthorization(q);if(C.status==="valid")continue;let M=jX.selectChallenge(C,Y);if(Y==="dns-01"){let D=pz(C.identifier.value),n=J.dns01TxtValue(M.token);await w.dnsProvider.setTxt(D,n),Q.push({name:D,value:n}),await cz(D,n,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(M.token,J.keyAuthorization(M.token)),f.push(M.token);await J.notifyChallengeReady(M.url),await J.pollAuthorization(q,{timeoutMs:w.timeoutMs})}let{privateKey:z,publicKey:B}=ez("ec",{namedCurve:"P-256"}),G=oz({domains:$,publicKey:B,privateKey:z});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(j,{timeoutMs:w.timeoutMs}),K=await J.downloadCertificate(T),{certPem:F,chainPem:N}=lz(K),R=N?`${F}${N}`:F,V=z.export({format:"pem",type:"pkcs8"}).toString(),L=new Date(new kK(F).validTo);return{certPem:F,keyPem:V,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:L}}finally{for(let{name:z,value:B}of Q)await w.dnsProvider?.removeTxt(z,B).catch(()=>{});for(let z of f)W.remove(z)}}class YB{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!tf(w))return!0;return af(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=tf(Y)?af(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class AB{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 CF(w,$){this[w]=IF.bind(null,$)}class wW{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(!sf(w))return!0;return of(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=sf(Y)?of(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 $W{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 SF(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function OF(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function hF(w){return w.getStats().size*2}function YW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&A0($[0])&&"id"in $[0]&&$[0].id===3&&A0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(A0($)&&A0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(A0(w)&&"arr"in w&&Array.isArray(w.arr)&&A0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&A0($[0])&&A0(w[0])){let A=[...$];for(let X of w)if(A0(X)&&"name"in X){if(!A.find((J)=>A0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(A0(X)&&"path"in X){if(!A.find((J)=>A0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>EX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!A0($)||!A0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(A0(X)&&A0(Y[A]))Y[A]=YW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&A0(X[0])&&A0(Y[A][0])){let J=[...X];for(let U of Y[A])if(A0(U)&&"name"in U){if(!J.find((j)=>A0(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(A0(U)&&"path"in U){if(!J.find((j)=>A0(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>EX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function EX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!EX(w[Y],$[Y]))return!1;return!0}if(A0(w)&&A0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!EX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function _F(w,$){if(!$B(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 YW($,A)}catch{return null}}catch{return null}}async function DF({name:w="",cwd:$,defaultConfig:Y}){let A=$||iU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=zX(A,`${U}${j}`),Q=await _F(W,Y);if(Q!==null)return Q}try{let U=zX(A,"package.json");if($B(U)){let j=(await import(U))[w];if(j&&typeof j==="object"&&!Array.isArray(j))try{return YW(Y,j)}catch{}}}catch{}return Y}function xF(w,$={}){let Y=fX.cwd();while(Y.includes("storage"))Y=$z(Y,"..");let A=$z(Y,w||"");if($?.relative)return dK(fX.cwd(),A);return A}async function kF(){try{let w=await DF({name:"clarity",defaultConfig:AX,cwd:fX.cwd(),endpoint:"",headers:{}});return{...AX,...w}}catch{return AX}}function W0(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZF(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dw<"u"){let w=dw.type;if(w==="renderer"||w==="worker")return!1;return!!(dw.versions&&(dw.versions.node||dw.versions.bun))}return!1}class JB{async format(w){let $=await ZF(),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 KX{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={...uU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new JB,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{...XX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...XX};return{...XX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uU.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 tK(this.config.logDirectory,Jz.F_OK|Jz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await aK(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:f$.from(w);try{if(!FU(this.currentLogFile))await TU(this.currentLogFile,"",{mode:420});if(A=Xz(this.currentLogFile,"a",420),rK(A,j,{flag:"a"}),Az(A),A!==void 0)KU(A),A=void 0;if((await f1(this.currentLogFile)).size===0){if(await TU(this.currentLogFile,j,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{KU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return z1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return z1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return z1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return EU(16).toString("hex")}generateKey(){return EU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=EU(16),A=nK("aes-256-gcm",$,Y),X=f$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:f$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Wz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(f$.from(f$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await f1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await f1(Y).catch(()=>null))try{if(await Uz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await vA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await TU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await f1(Y).catch(()=>null))await Uz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await cA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await vA(z1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Yz(w),A=pK($),X=Wz();await sK(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()})),FU(this.currentLogFile))try{let w=Xz(this.currentLogFile,"r+");Az(w),KU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await cA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await vA(z1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?e.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=h0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${e.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let Q=KB[w],f=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
|
|
65
|
+
`:""}}function pz(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function rf(w){return new Promise(($)=>setTimeout($,w))}function VK(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function G$(w,$){return Buffer.concat([Buffer.from([w]),VK($.length),$])}function rz(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return G$(2,$)}function D$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return G$(6,Buffer.from(Y))}function Qw(...w){return G$(48,Buffer.concat(w))}function xU(...w){return G$(49,Buffer.concat(w))}function kU(w){return G$(3,Buffer.concat([Buffer.from([0]),w]))}function tz(w){return G$(4,w)}function az(w){return G$(12,Buffer.from(w,"utf8"))}function ZU(w,$,Y){let A=128|(Y?32:0)|w;return G$(A,$)}function xK(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=DU($.x),A=DU($.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function sz(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(xU(Qw(D$(hK),az($[0])))),J=Qw(Qw(D$(LK),D$(SK)),kU(xK(Y))),U=$.map((K)=>ZU(2,Buffer.from(K,"ascii"),!1)),j=Qw(...U),W=Qw(D$(DK),tz(j)),Q=Qw(W),f=Qw(D$(_K),xU(Q)),z=ZU(0,f,!0),B=Qw(rz(0),X,J,z),G=CK("sha256",B,A),T=Qw(D$(OK));return Qw(B,T,kU(G))}function oz(w){return sz(w).toString("base64url")}function ZK(w){if(w){let{createPrivateKey:X,createPublicKey:J}=RK("node:crypto"),U=X(w),j=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:j,pem:w}}let{privateKey:$,publicKey:Y}=ez("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function oU(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?nz:dz),X=ZK(w.accountKeyPem),J=new jX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:j}=await J.newOrder($),W=w.http01Store??CX,Q=[],f=[];try{for(let N of U.authorizations){let C=await J.getAuthorization(N);if(C.status==="valid")continue;let M=jX.selectChallenge(C,Y);if(Y==="dns-01"){let D=pz(C.identifier.value),n=J.dns01TxtValue(M.token);await w.dnsProvider.setTxt(D,n),Q.push({name:D,value:n}),await cz(D,n,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(M.token,J.keyAuthorization(M.token)),f.push(M.token);await J.notifyChallengeReady(M.url),await J.pollAuthorization(N,{timeoutMs:w.timeoutMs})}let{privateKey:z,publicKey:B}=ez("ec",{namedCurve:"P-256"}),G=oz({domains:$,publicKey:B,privateKey:z});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(j,{timeoutMs:w.timeoutMs}),K=await J.downloadCertificate(T),{certPem:F,chainPem:q}=lz(K),R=q?`${F}${q}`:F,V=z.export({format:"pem",type:"pkcs8"}).toString(),L=new Date(new kK(F).validTo);return{certPem:F,keyPem:V,chainPem:q,fullChainPem:R,accountKeyPem:X.pem,notAfter:L}}finally{for(let{name:z,value:B}of Q)await w.dnsProvider?.removeTxt(z,B).catch(()=>{});for(let z of f)W.remove(z)}}class YB{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!tf(w))return!0;return af(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=tf(Y)?af(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class AB{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 CF(w,$){this[w]=IF.bind(null,$)}class wW{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(!sf(w))return!0;return of(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=sf(Y)?of(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 $W{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 SF(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function OF(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function hF(w){return w.getStats().size*2}function YW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&A0($[0])&&"id"in $[0]&&$[0].id===3&&A0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(A0($)&&A0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(A0(w)&&"arr"in w&&Array.isArray(w.arr)&&A0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&A0($[0])&&A0(w[0])){let A=[...$];for(let X of w)if(A0(X)&&"name"in X){if(!A.find((J)=>A0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(A0(X)&&"path"in X){if(!A.find((J)=>A0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>EX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!A0($)||!A0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(A0(X)&&A0(Y[A]))Y[A]=YW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&A0(X[0])&&A0(Y[A][0])){let J=[...X];for(let U of Y[A])if(A0(U)&&"name"in U){if(!J.find((j)=>A0(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(A0(U)&&"path"in U){if(!J.find((j)=>A0(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>EX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function EX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!EX(w[Y],$[Y]))return!1;return!0}if(A0(w)&&A0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!EX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function _F(w,$){if(!$B(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 YW($,A)}catch{return null}}catch{return null}}async function DF({name:w="",cwd:$,defaultConfig:Y}){let A=$||iU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=zX(A,`${U}${j}`),Q=await _F(W,Y);if(Q!==null)return Q}try{let U=zX(A,"package.json");if($B(U)){let j=(await import(U))[w];if(j&&typeof j==="object"&&!Array.isArray(j))try{return YW(Y,j)}catch{}}}catch{}return Y}function xF(w,$={}){let Y=fX.cwd();while(Y.includes("storage"))Y=$z(Y,"..");let A=$z(Y,w||"");if($?.relative)return dK(fX.cwd(),A);return A}async function kF(){try{let w=await DF({name:"clarity",defaultConfig:AX,cwd:fX.cwd(),endpoint:"",headers:{}});return{...AX,...w}}catch{return AX}}function W0(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ZF(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dw<"u"){let w=dw.type;if(w==="renderer"||w==="worker")return!1;return!!(dw.versions&&(dw.versions.node||dw.versions.bun))}return!1}class JB{async format(w){let $=await ZF(),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 KX{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={...uU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new JB,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{...XX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...XX};return{...XX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uU.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 tK(this.config.logDirectory,Jz.F_OK|Jz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await aK(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:f$.from(w);try{if(!FU(this.currentLogFile))await TU(this.currentLogFile,"",{mode:420});if(A=Xz(this.currentLogFile,"a",420),rK(A,j,{flag:"a"}),Az(A),A!==void 0)KU(A),A=void 0;if((await f1(this.currentLogFile)).size===0){if(await TU(this.currentLogFile,j,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{KU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return z1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return z1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return z1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return EU(16).toString("hex")}generateKey(){return EU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=EU(16),A=nK("aes-256-gcm",$,Y),X=f$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:f$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Wz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(f$.from(f$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await f1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await f1(Y).catch(()=>null))try{if(await Uz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await vA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await TU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await f1(Y).catch(()=>null))await Uz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await cA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await vA(z1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Yz(w),A=pK($),X=Wz();await sK(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()})),FU(this.currentLogFile))try{let w=Xz(this.currentLogFile,"r+");Az(w),KU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await cA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await vA(z1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?e.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=h0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${e.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let Q=KB[w],f=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
|
|
66
66
|
`);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:e.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
|
|
67
67
|
`;if(j)W+=`${j}
|
|
68
68
|
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:e.blue("◐"),tag:Y,message:`${e.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
|
|
@@ -70,7 +70,7 @@ export type ConfigOf = Config
|
|
|
70
70
|
`),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:e.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
|
|
71
71
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${e.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();h0.stdin.removeListener("data",Y);try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!1)}catch{}h0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!0)}catch{}h0.stdin.resume(),h0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,j)=>{if(j==="%")return"%";if(J>=$.length)return U;let W=$[J++];switch(j){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!W0()){let X=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",J=e.blue("◐");console.error(`${J} ${X} ${e.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
72
72
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;h0.stdout.write(`${"\r".padEnd(h0.stdout.columns||80)}\r`),this.log(X,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||W0()||!h0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=e.green("━".repeat(A)),U=e.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?e.green("✓"):e.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${e.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=h0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,h0.stdout.write(w.lastRenderedLine),$)h0.stdout.write(`
|
|
73
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await cA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=z1(this.config.logDirectory,A);if(w.before)try{if((await f1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await vA(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 YX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&t($[0])&&"id"in $[0]&&$[0].id===3&&t($[1])&&"id"in $[1]&&$[1].id===4)return $;if(t($)&&t(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(t(w)&&"arr"in w&&Array.isArray(w.arr)&&t($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&t($[0])&&t(w[0])){let A=[...$];for(let X of w)if(t(X)&&"name"in X){if(!A.find((J)=>t(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(t(X)&&"path"in X){if(!A.find((J)=>t(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>FX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!t($)||!t(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(t(X)&&t(Y[A]))Y[A]=YX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&t(X[0])&&t(Y[A][0])){let J=[...X];for(let U of Y[A])if(t(U)&&"name"in U){if(!J.find((j)=>t(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(t(U)&&"path"in U){if(!J.find((j)=>t(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>FX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function AW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:YX(w,$);if(Array.isArray(w))return Y==="replace"?$:YX(w,$);if(!t($)||!t(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=YX(U,J);else if(t(J)&&t(U))A[X]=AW(U,J,Y);else A[X]=J}return A}function FX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!FX(w[Y],$[Y]))return!1;return!0}if(t(w)&&t($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!FX(w[X],$[X]))return!1}return!0}return!1}function t(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function oA(w,$,Y="replace"){if(!wB(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 AW($,X,Y)}catch{return null}}catch{return null}}function PF(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=JY.env[G]||JY.env[T];if(K!==void 0){if(Y)D0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function iF({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?PF(w,X,J):X,Q=Y||JY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,m0(Q,"config"),m0(Q,".config"),A?m0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)D0.info(`Searching for configuration in: ${F}`);let N=[m0(Q,"config"),m0(Q,".config")].concat(A?[m0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from: ${L}`);return q}}}if(w){let F=m0(GU(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${F}`);for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let F=m0(GU(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let F=GU(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let F=m0(Q,"package.json");if(wB(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)D0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return AW(W,R,j)}catch(V){if(J)D0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)D0.warn("Failed to load package.json:",F)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function bF(w,$={}){let Y=QX.cwd();while(Y.includes("storage"))Y=wz(Y,"..");let A=wz(Y,w||"");if($?.relative)return mK(QX.cwd(),A);return A}async function uF(){try{let w=await iF({name:"clarity",alias:"logging",defaultConfig:JX,cwd:QX.cwd()});return{...JX,...w||{}}}catch{return JX}}function T0(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cF(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nw<"u"){let w=nw.type;if(w==="renderer"||w==="worker")return!1;return!!(nw.versions&&(nw.versions.node||nw.versions.bun))}return!1}class UB{async format(w){let $=await cF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:K1.pid,hostname:$(),environment:K1.env.NODE_ENV||"development",platform:K1.platform,version:K1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:K1.env.NODE_ENV||K1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class TX{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={...cU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new UB,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},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{...UX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...UX};return{...UX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:cU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await YF(this.config.logDirectory,zz.F_OK|zz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await AF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:vw.from(w);try{if(!mA(this.currentLogFile))await HU(this.currentLogFile,"",{mode:420});if(A=fz(this.currentLogFile,"a",420),$F(A,j,{flag:"a"}),Qz(A),A!==void 0)qU(A),A=void 0;if((await G1(this.currentLogFile)).size===0){if(await HU(this.currentLogFile,j,{flag:"w",mode:420}),(await G1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{qU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return E1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return E1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return E1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return NU(16).toString("hex")}generateKey(){return NU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=NU(16),A=oK("aes-256-gcm",$,Y),X=vw.isBuffer(w)?w:vw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=vw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Gz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(vw.from(vw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await G1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await G1(Y).catch(()=>null))try{if(await Bz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await dA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await HU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await G1(Y).catch(()=>null))await Bz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await gA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await dA(E1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=jz(w),A=wF($),X=Gz();await UF(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()})),mA(this.currentLogFile))try{let w=fz(this.currentLogFile,"r+");Qz(w),qU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await dA(E1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof p.env.NO_COLOR<"u",$=p.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=p.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${u.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=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("../"))$=JF($);else return null;return mA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":FB[w],B=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
73
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await cA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=z1(this.config.logDirectory,A);if(w.before)try{if((await f1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await vA(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 YX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&t($[0])&&"id"in $[0]&&$[0].id===3&&t($[1])&&"id"in $[1]&&$[1].id===4)return $;if(t($)&&t(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(t(w)&&"arr"in w&&Array.isArray(w.arr)&&t($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&t($[0])&&t(w[0])){let A=[...$];for(let X of w)if(t(X)&&"name"in X){if(!A.find((J)=>t(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(t(X)&&"path"in X){if(!A.find((J)=>t(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>FX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!t($)||!t(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(t(X)&&t(Y[A]))Y[A]=YX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&t(X[0])&&t(Y[A][0])){let J=[...X];for(let U of Y[A])if(t(U)&&"name"in U){if(!J.find((j)=>t(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(t(U)&&"path"in U){if(!J.find((j)=>t(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>FX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function AW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:YX(w,$);if(Array.isArray(w))return Y==="replace"?$:YX(w,$);if(!t($)||!t(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=YX(U,J);else if(t(J)&&t(U))A[X]=AW(U,J,Y);else A[X]=J}return A}function FX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!FX(w[Y],$[Y]))return!1;return!0}if(t(w)&&t($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!FX(w[X],$[X]))return!1}return!0}return!1}function t(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function oA(w,$,Y="replace"){if(!wB(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 AW($,X,Y)}catch{return null}}catch{return null}}function PF(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=JY.env[G]||JY.env[T];if(K!==void 0){if(Y)D0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((q)=>q.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function iF({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?PF(w,X,J):X,Q=Y||JY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,m0(Q,"config"),m0(Q,".config"),A?m0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)D0.info(`Searching for configuration in: ${F}`);let q=[m0(Q,"config"),m0(Q,".config")].concat(A?[m0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let R of q)for(let V of f){let L=m0(F,`${R}${V}`),N=await oA(L,W,j);if(N!==null){if(J)D0.success(`Configuration loaded from: ${L}`);return N}}}if(w){let F=m0(GU(),".config",w),q=["config",`${w}.config`];if($)q.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${F}`);for(let R of q)for(let V of f){let L=m0(F,`${R}${V}`),N=await oA(L,W,j);if(N!==null){if(J)D0.success(`Configuration loaded from user config directory: ${L}`);return N}}}if(w){let F=m0(GU(),".config"),q=[`.${w}.config`];if($)q.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of q)for(let V of f){let L=m0(F,`${R}${V}`),N=await oA(L,W,j);if(N!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${L}`);return N}}}if(w){let F=GU(),q=[`.${w}.config`,`.${w}`];if($)q.push(`.${$}.config`),q.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of q)for(let V of f){let L=m0(F,`${R}${V}`),N=await oA(L,W,j);if(N!==null){if(J)D0.success(`Configuration loaded from user home directory: ${L}`);return N}}}try{let F=m0(Q,"package.json");if(wB(F)){let q=await import(F),R=q[w];if(!R&&$){if(R=q[$],R&&J)D0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===q[w]?w:$}`);return AW(W,R,j)}catch(V){if(J)D0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)D0.warn("Failed to load package.json:",F)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function bF(w,$={}){let Y=QX.cwd();while(Y.includes("storage"))Y=wz(Y,"..");let A=wz(Y,w||"");if($?.relative)return mK(QX.cwd(),A);return A}async function uF(){try{let w=await iF({name:"clarity",alias:"logging",defaultConfig:JX,cwd:QX.cwd()});return{...JX,...w||{}}}catch{return JX}}function T0(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cF(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nw<"u"){let w=nw.type;if(w==="renderer"||w==="worker")return!1;return!!(nw.versions&&(nw.versions.node||nw.versions.bun))}return!1}class UB{async format(w){let $=await cF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:K1.pid,hostname:$(),environment:K1.env.NODE_ENV||"development",platform:K1.platform,version:K1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:K1.env.NODE_ENV||K1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class TX{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={...cU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new UB,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},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{...UX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...UX};return{...UX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:cU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await YF(this.config.logDirectory,zz.F_OK|zz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await AF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:vw.from(w);try{if(!mA(this.currentLogFile))await HU(this.currentLogFile,"",{mode:420});if(A=fz(this.currentLogFile,"a",420),$F(A,j,{flag:"a"}),Qz(A),A!==void 0)NU(A),A=void 0;if((await G1(this.currentLogFile)).size===0){if(await HU(this.currentLogFile,j,{flag:"w",mode:420}),(await G1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{NU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return E1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return E1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return E1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return qU(16).toString("hex")}generateKey(){return qU(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=qU(16),A=oK("aes-256-gcm",$,Y),X=vw.isBuffer(w)?w:vw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=vw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Gz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(vw.from(vw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await G1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await G1(Y).catch(()=>null))try{if(await Bz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await dA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await HU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await G1(Y).catch(()=>null))await Bz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await gA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await dA(E1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=jz(w),A=wF($),X=Gz();await UF(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()})),mA(this.currentLogFile))try{let w=fz(this.currentLogFile,"r+");Qz(w),NU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await dA(E1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof p.env.NO_COLOR<"u",$=p.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=p.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${u.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=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("../"))$=JF($);else return null;return mA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":FB[w],B=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
74
74
|
`);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
|
|
75
75
|
`;if(j)f+=`${j}
|
|
76
76
|
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&p.stdout.isTTY)p.stdout.write(`
|
|
@@ -79,7 +79,7 @@ export type ConfigOf = Config
|
|
|
79
79
|
`),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(f),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
80
80
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(T0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();p.stdin.removeListener("data",Y);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${U} ${u.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
81
81
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=p.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,p.stdout.write(w.lastRenderedLine),$)p.stdout.write(`
|
|
82
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!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(T0()){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 X=E1(this.config.logDirectory,A);if(w.before)try{if((await G1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await dA(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 WB(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function jB(w){return w instanceof e0}function vF(w){return w instanceof
|
|
82
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!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(T0()){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 X=E1(this.config.logDirectory,A);if(w.before)try{if((await G1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await dA(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 WB(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function jB(w){return w instanceof e0}function vF(w){return w instanceof qX}function mF(w){if(jB(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 LX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return QY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=nA.env[W]||(Q?nA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=nA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof NX)throw z;throw B$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw B$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(nA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
83
83
|
|
|
84
84
|
`;for(let A of w)Y+=`${A.key}
|
|
85
85
|
`,Y+=` Type: ${A.type}
|
|
@@ -91,25 +91,25 @@ export type ConfigOf = Config
|
|
|
91
91
|
`;Y+=`| Variable | Type | Description | Example |
|
|
92
92
|
`,Y+=`|----------|------|-------------|----------|
|
|
93
93
|
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
94
|
-
`;return Y}}function gF(w,$){let Y=GB("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function QB(w,$,Y={}){return fB(w,$,Y,new WeakMap)}function fB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return zB(w,$,X,A);if(!zw($)||!zw(w))return $;return pF(w,$,Y,A)}function zB(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 dF(w,$);case"smart":return nF(w,$,A);default:return $}return $}function dF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>bU(X,A)))Y.push(A);return Y}function nF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return lF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function lF(w,$,Y){let A=[...$];for(let X of w){if(!zw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>zw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function pF(w,$,Y,A){let X=$;if(zw(X)&&A.has(X))return A.get(X);let J={...w};if(zw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(zw(j)&&zw(W))J[U]=fB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=zB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function XW(w,$,Y="replace"){return QB(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bU(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(!bU(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(!bU(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class SX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=H1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!lA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new UY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new UY(w,Error("Configuration must export a valid object"),"unknown");let T={config:XW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)H1.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?B$.configLoad(w,Q):B$.configLoad(w,Error(String(Q)))}};if(U)return QY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(RU($,`${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 WB(async()=>{return lA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!lA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=RU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=RU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!lA(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 JW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await QY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!WF($))throw new WY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new WY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:NB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UW{fileLoader=new SX;envProcessor=new LX;validator=new JW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)qw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw qw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||x$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(g0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw B$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?YY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)qw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)qw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?YY(w,Y,X):Y,j=[g0(Q1(),".config",w),g0(Q1(),".config"),Q1()];for(let W of j){if(X)qw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)qw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?YY(w,A,J):A;try{let W=g0(Y,"package.json");if(!PU(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)qw.success(`Configuration loaded from package.json: ${z}`);return{config:XW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)qw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:YY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw B$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return H1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);H1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(Q1(),".config",w),g0(Q1(),".config"),Q1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Mz(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 rF(w){return rw.loadConfig({...w,__strictErrorHandling:!0})}async function BB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await rw.loadConfig(w);else A=await rw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)qw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await rw.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function tF(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await rw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Mz(Y)))return(await rw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await rw.loadConfig({...w,cwd:w.cwd||x$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Mz($)))return(await rw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function aF(w,$,Y="replace"){let A=new SX;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 LX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=x$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function sF(w){let $=g0(x$.cwd(),w.configDir),Y=g0(x$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!PU(ef(A)))bK(ef(A),{recursive:!0,mode:511});let X=PU($)?uK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${VT}
|
|
94
|
+
`;return Y}}function gF(w,$){let Y=GB("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function QB(w,$,Y={}){return fB(w,$,Y,new WeakMap)}function fB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return zB(w,$,X,A);if(!zw($)||!zw(w))return $;return pF(w,$,Y,A)}function zB(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 dF(w,$);case"smart":return nF(w,$,A);default:return $}return $}function dF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>bU(X,A)))Y.push(A);return Y}function nF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return lF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function lF(w,$,Y){let A=[...$];for(let X of w){if(!zw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>zw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function pF(w,$,Y,A){let X=$;if(zw(X)&&A.has(X))return A.get(X);let J={...w};if(zw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(zw(j)&&zw(W))J[U]=fB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=zB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function XW(w,$,Y="replace"){return QB(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function bU(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(!bU(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(!bU(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class SX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=H1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!lA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new UY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new UY(w,Error("Configuration must export a valid object"),"unknown");let T={config:XW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)H1.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?B$.configLoad(w,Q):B$.configLoad(w,Error(String(Q)))}};if(U)return QY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(RU($,`${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 WB(async()=>{return lA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!lA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=RU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=RU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!lA(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 JW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await QY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!WF($))throw new WY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new WY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:qB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UW{fileLoader=new SX;envProcessor=new LX;validator=new JW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Nw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Nw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||x$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(g0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw B$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?YY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Nw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Nw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?YY(w,Y,X):Y,j=[g0(Q1(),".config",w),g0(Q1(),".config"),Q1()];for(let W of j){if(X)Nw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Nw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?YY(w,A,J):A;try{let W=g0(Y,"package.json");if(!PU(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Nw.success(`Configuration loaded from package.json: ${z}`);return{config:XW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Nw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:YY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw B$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return H1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);H1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(Q1(),".config",w),g0(Q1(),".config"),Q1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Mz(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 rF(w){return rw.loadConfig({...w,__strictErrorHandling:!0})}async function BB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await rw.loadConfig(w);else A=await rw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Nw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await rw.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function tF(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await rw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Mz(Y)))return(await rw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await rw.loadConfig({...w,cwd:w.cwd||x$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Mz($)))return(await rw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function aF(w,$,Y="replace"){let A=new SX;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 LX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=x$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function sF(w){let $=g0(x$.cwd(),w.configDir),Y=g0(x$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!PU(ef(A)))bK(ef(A),{recursive:!0,mode:511});let X=PU($)?uK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${VT}
|
|
95
95
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
96
|
-
`;cK(A,J,{mode:438})}function oF(w){let $=null,Y=null,A=()=>{if(!Y)Y=BB(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)
|
|
96
|
+
`;cK(A,J,{mode:438})}function oF(w){let $=null,Y=null,A=()=>{if(!Y)Y=BB(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Nw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function eF(w){let $=Ez(fF.cwd(),w?.configDir||"./config");function Y(){if(!jF($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=QF($).filter((W)=>X.has(MU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=MU(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=MU(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",j=X.length?`{
|
|
97
97
|
${X.map((W)=>{let Q=Ez($,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${Q}').default`}).join(`,
|
|
98
98
|
`)}
|
|
99
99
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
100
100
|
export type ConfigByName = ${j}
|
|
101
101
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
102
102
|
export type ConfigOf = Config
|
|
103
|
-
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function ST(w,$={}){let Y=BX.cwd();while(Y.includes("storage"))Y=Kz(Y,"..");let A=Kz(Y,w||"");if($?.relative)return BF(BX.cwd(),A);return A}function q0(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hT(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lw<"u"){let w=lw.type;if(w==="renderer"||w==="worker")return!1;return!!(lw.versions&&(lw.versions.node||lw.versions.bun))}return!1}class MB{async format(w){let $=await hT(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:N1.pid,hostname:$(),environment:N1.env.NODE_ENV||"development",platform:N1.platform,version:N1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:N1.env.NODE_ENV||N1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class OX{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={...HX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new MB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??r.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{..._U,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{..._U};return{..._U,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:HX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await TF(this.config.logDirectory,qz.F_OK|qz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await NF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:mw.from(w);try{if(!pA(this.currentLogFile))await CU(this.currentLogFile,"",{mode:420});if(A=Nz(this.currentLogFile,"a",420),FF(A,j,{flag:"a"}),Tz(A),A!==void 0)IU(A),A=void 0;if((await F1(this.currentLogFile)).size===0){if(await CU(this.currentLogFile,j,{flag:"w",mode:420}),(await F1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{IU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return T1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return T1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return yU(16).toString("hex")}generateKey(){return yU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=yU(16),A=GF("aes-256-gcm",$,Y),X=mw.isBuffer(w)?w:mw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=mw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Rz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(mw.from(mw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let w=await F1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await F1(Y).catch(()=>null))try{if(await Hz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await tA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await CU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await F1(Y).catch(()=>null))await Hz(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(T1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Fz(w),A=KF($),X=Rz();await RF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),pA(this.currentLogFile))try{let w=Nz(this.currentLogFile,"r+");Tz(w),IU(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(T1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let w=typeof r.env.NO_COLOR<"u",$=r.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof r.stderr<"u"&&r.stderr.isTTY||typeof r.stdout<"u"&&r.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=r.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${m.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(q0())return!1;let w=r.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=r.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(qF($)||$.startsWith("./")||$.startsWith("../"))$=HF($);else return null;return pA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":ZT[w],B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
104
|
-
`);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!
|
|
103
|
+
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function ST(w,$={}){let Y=BX.cwd();while(Y.includes("storage"))Y=Kz(Y,"..");let A=Kz(Y,w||"");if($?.relative)return BF(BX.cwd(),A);return A}function N0(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hT(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lw<"u"){let w=lw.type;if(w==="renderer"||w==="worker")return!1;return!!(lw.versions&&(lw.versions.node||lw.versions.bun))}return!1}class MB{async format(w){let $=await hT(),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 OX{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={...HX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new MB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??r.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{..._U,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{..._U};return{..._U,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:HX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await TF(this.config.logDirectory,Nz.F_OK|Nz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await qF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:mw.from(w);try{if(!pA(this.currentLogFile))await CU(this.currentLogFile,"",{mode:420});if(A=qz(this.currentLogFile,"a",420),FF(A,j,{flag:"a"}),Tz(A),A!==void 0)IU(A),A=void 0;if((await F1(this.currentLogFile)).size===0){if(await CU(this.currentLogFile,j,{flag:"w",mode:420}),(await F1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{IU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return T1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return T1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return yU(16).toString("hex")}generateKey(){return yU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=yU(16),A=GF("aes-256-gcm",$,Y),X=mw.isBuffer(w)?w:mw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=mw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Rz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(mw.from(mw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let w=await F1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await F1(Y).catch(()=>null))try{if(await Hz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await tA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await CU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await F1(Y).catch(()=>null))await Hz(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(T1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Fz(w),A=KF($),X=Rz();await RF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),pA(this.currentLogFile))try{let w=qz(this.currentLogFile,"r+");Tz(w),IU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await rA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await tA(T1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let w=typeof r.env.NO_COLOR<"u",$=r.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof r.stderr<"u"&&r.stderr.isTTY||typeof r.stdout<"u"&&r.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=r.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${m.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(N0())return!1;let w=r.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=r.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(NF($)||$.startsWith("./")||$.startsWith("../"))$=HF($);else return null;return pA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":ZT[w],B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
104
|
+
`);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
|
|
105
105
|
`;if(j)f+=`${j}
|
|
106
|
-
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
107
|
-
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
108
|
-
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":m.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!
|
|
109
|
-
`),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(f),showTimestamp:!1}))}else if(!
|
|
110
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(
|
|
106
|
+
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&r.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!N0()&&r.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!N0()&&r.stdout.isTTY)r.stdout.write(`
|
|
107
|
+
`);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&r.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
|
|
108
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":m.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!N0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new OX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!pA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=mw.isBuffer(w)?w:mw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=EF("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=mw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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 j=X.split(`
|
|
109
|
+
`),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(f),showTimestamp:!1}))}else if(!N0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
110
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();r.stdin.removeListener("data",Y);try{if(typeof r.stdin.setRawMode==="function")r.stdin.setRawMode(!1)}catch{}r.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof r.stdin.setRawMode==="function")r.stdin.setRawMode(!0)}catch{}r.stdin.resume(),r.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${j}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
111
111
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!r.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=r.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,r.stdout.write(w.lastRenderedLine),$)r.stdout.write(`
|
|
112
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||
|
|
112
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||N0()||!r.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 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=T1(this.config.logDirectory,A);if(w.before)try{if((await F1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await 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 PT(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class jW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return eU.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=aA.env[W]||(Q?aA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=aA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof WW)throw z;throw R1.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw R1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(aA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
113
113
|
|
|
114
114
|
`;for(let A of w)Y+=`${A.key}
|
|
115
115
|
`,Y+=` Type: ${A.type}
|
|
@@ -121,15 +121,15 @@ export type ConfigOf = Config
|
|
|
121
121
|
`;Y+=`| Variable | Type | Description | Example |
|
|
122
122
|
`,Y+=`|----------|------|-------------|----------|
|
|
123
123
|
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
124
|
-
`;return Y}}function iT(w,$,Y={}){return hB(w,$,Y,new WeakMap)}function hB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return _B(w,$,X,A);if(!Bw($)||!Bw(w))return $;return vT(w,$,Y,A)}function _B(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 bT(w,$);case"smart":return uT(w,$,A);default:return $}return $}function bT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>pU(X,A)))Y.push(A);return Y}function uT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Bw($[0])&&Bw(w[0]))return cT(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 cT(w,$,Y){let A=[...$];for(let X of w){if(!Bw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>Bw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function vT(w,$,Y,A){let X=$;if(Bw(X)&&A.has(X))return A.get(X);let J={...w};if(Bw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Bw(j)&&Bw(W))J[U]=hB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=_B(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function DB(w,$,Y="replace"){return iT(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function pU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!pU(w[Y],$[Y]))return!1;return!0}if(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(!pU(w[X],$[X]))return!1}return!0}return!1}function Bw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class xB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=GX.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!sA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new RX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new RX(w,Error("Configuration must export a valid object"),"unknown");let T={config:DB($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)GX.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?R1.configLoad(w,Q):R1.configLoad(w,Error(String(Q)))}};if(U)return eU.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(VU($,`${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 PT(async()=>{return sA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!sA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=VU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=VU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!sA(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 kB{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await eU.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!MF($))throw new MX($,[{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 MX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:mT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function gT(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 ZB{fileLoader=new xB;envProcessor=new jW;validator=new kB;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)gw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw gw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||VX.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(fw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw R1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${gT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?eA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)gw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)gw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?eA(w,Y,X):Y,j=[fw(j1(),".config",w),fw(j1(),".config"),j1()];for(let W of j){if(X)gw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)gw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?eA(w,A,J):A;try{let W=fw(Y,"package.json");if(!PK(W))return null;let Q={};try{Q=JSON.parse(iK(W,"utf8"))}catch(B){if(J)gw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)gw.success(`Configuration loaded from package.json: ${z}`);return{config:DB(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)gw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:eA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw R1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return GX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);GX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,fw(w,"config"),fw(w,".config"),$?fw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(fw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[fw(j1(),".config",w),fw(j1(),".config"),j1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function eA(w,$,Y=!1){let A=new jW,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=VX.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function bB(w){return rU.readFileSync(w,"utf8")}function tU(w,$){let Y=[];function A(X){let J;try{J=rU.readdirSync(X)}catch{return}for(let U of J){let j=Nw.join(X,U);try{if(rU.statSync(j).isDirectory())A(j);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function S(w,$,Y){if(Y||f0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function uB(){return iB.env.SUDO_PASSWORD}function aT(w){let $=w.toLowerCase();return rT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function yX(w){if(Array.isArray(w))return w.map((Y)=>yX(Y));if(typeof w==="string")return tT.test(w)?Zz:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(aT(Y)){$[Y]=Zz;continue}$[Y]=yX(A)}return $}function hX(w){return JSON.stringify(yX(w))}function sT(w){let $=uB();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function z$(w,$={}){let Y=sT(w);try{let{stdout:A,stderr:X}=await pT(Y,{cwd:$.cwd||iB.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
|
|
125
|
-
Error: ${A.message}`);throw X.stack=A.stack,X}}function cB(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 QW(w){let $=
|
|
124
|
+
`;return Y}}function iT(w,$,Y={}){return hB(w,$,Y,new WeakMap)}function hB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return _B(w,$,X,A);if(!Bw($)||!Bw(w))return $;return vT(w,$,Y,A)}function _B(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 bT(w,$);case"smart":return uT(w,$,A);default:return $}return $}function bT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>pU(X,A)))Y.push(A);return Y}function uT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Bw($[0])&&Bw(w[0]))return cT(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 cT(w,$,Y){let A=[...$];for(let X of w){if(!Bw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>Bw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function vT(w,$,Y,A){let X=$;if(Bw(X)&&A.has(X))return A.get(X);let J={...w};if(Bw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Bw(j)&&Bw(W))J[U]=hB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=_B(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function DB(w,$,Y="replace"){return iT(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function pU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!pU(w[Y],$[Y]))return!1;return!0}if(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(!pU(w[X],$[X]))return!1}return!0}return!1}function Bw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class xB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=GX.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!sA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new RX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new RX(w,Error("Configuration must export a valid object"),"unknown");let T={config:DB($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)GX.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?R1.configLoad(w,Q):R1.configLoad(w,Error(String(Q)))}};if(U)return eU.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(VU($,`${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 PT(async()=>{return sA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!sA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=VU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=VU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!sA(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 kB{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await eU.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!MF($))throw new MX($,[{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 MX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:mT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function gT(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 ZB{fileLoader=new xB;envProcessor=new jW;validator=new kB;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)gw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw gw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||VX.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(fw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw R1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${gT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?eA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)gw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)gw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?eA(w,Y,X):Y,j=[fw(j1(),".config",w),fw(j1(),".config"),j1()];for(let W of j){if(X)gw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)gw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?eA(w,A,J):A;try{let W=fw(Y,"package.json");if(!PK(W))return null;let Q={};try{Q=JSON.parse(iK(W,"utf8"))}catch(B){if(J)gw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)gw.success(`Configuration loaded from package.json: ${z}`);return{config:DB(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)gw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:eA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw R1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return GX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);GX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,fw(w,"config"),fw(w,".config"),$?fw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(fw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[fw(j1(),".config",w),fw(j1(),".config"),j1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function eA(w,$,Y=!1){let A=new jW,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=VX.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function bB(w){return rU.readFileSync(w,"utf8")}function tU(w,$){let Y=[];function A(X){let J;try{J=rU.readdirSync(X)}catch{return}for(let U of J){let j=qw.join(X,U);try{if(rU.statSync(j).isDirectory())A(j);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function S(w,$,Y){if(Y||f0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function uB(){return iB.env.SUDO_PASSWORD}function aT(w){let $=w.toLowerCase();return rT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function yX(w){if(Array.isArray(w))return w.map((Y)=>yX(Y));if(typeof w==="string")return tT.test(w)?Zz:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(aT(Y)){$[Y]=Zz;continue}$[Y]=yX(A)}return $}function hX(w){return JSON.stringify(yX(w))}function sT(w){let $=uB();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function z$(w,$={}){let Y=sT(w);try{let{stdout:A,stderr:X}=await pT(Y,{cwd:$.cwd||iB.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
|
|
125
|
+
Error: ${A.message}`);throw X.stack=A.stack,X}}function cB(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 QW(w){let $=qw.join(nT.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:f0.basePath&&f0.basePath.trim()!==""?f0.basePath:$,A=w.certPath?qw.isAbsolute(w.certPath)?w.certPath:qw.join(Y,w.certPath):qw.join(Y,f0.certPath),X=w.keyPath?qw.isAbsolute(w.keyPath)?w.keyPath:qw.join(Y,w.keyPath):qw.join(Y,f0.keyPath),J=w.caCertPath?qw.isAbsolute(w.caCertPath)?w.caCertPath:qw.join(Y,w.caCertPath):qw.join(Y,f0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function vB(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return S(O.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function fW(w){let $=w.notBeforeDays??Hw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:Hw.DEFAULT_VALIDITY_DAYS);S(O.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),S(O.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function AY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function $w(w,$){let Y=AY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function jY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return $w(Rw.OID,Buffer.from(Y))}function aU(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return $w(Rw.INTEGER,$)}function mB(w,$=0){return $w(Rw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function gB(w){return $w(Rw.OCTET_STRING,w)}function ww(...w){return $w(Rw.SEQUENCE,Buffer.concat(w))}function oT(...w){return $w(Rw.SET,Buffer.concat(w))}function eT(w){return $w(Rw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function w7(w){return $w(Rw.UTF8_STRING,Buffer.from(w,"utf8"))}function $7(){return Buffer.from([Rw.NULL,0])}function Pz(w,$,Y=!0){let A=160|w|(Y?0:0),X=AY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function iz(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return $w(Rw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),j=w.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${j}Z`;return $w(Rw.UTC_TIME,Buffer.from(W,"ascii"))}}function Y7(w,$){return ww(iz(w),iz($))}function bz(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"?eT(Y.value):w7(Y.value),J=ww(jY(A),X);$.push(oT(J))}return ww(...$)}function dB(w){return ww(jY(w),$7())}function A7(w){return w.export({type:"spki",format:"der"})}function X7(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],j=8-J.length-U.length,W=Array.from({length:j},()=>"0");$=[...J,...W,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function J7(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=AY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=X7(Y.ip),X=AY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=AY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return ww(...$)}function U7(w,$){if(w){if($!==void 0)return ww($w(1,Buffer.from([255])),aU($));return ww($w(1,Buffer.from([255])))}return ww()}function W7(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 mB(Buffer.from([$]),Y)}function j7(w){let $=[];if(w.serverAuth)$.push(jY(d0.SERVER_AUTH));if(w.clientAuth)$.push(jY(d0.CLIENT_AUTH));return ww(...$)}function $Y(w,$,Y){let A=[jY(w)];if($)A.push($w(1,Buffer.from([255])));return A.push(gB(Y)),ww(...A)}function Q7(w){let $=[];if($.push(Pz(0,aU(2))),$.push(aU(w.serialNumber)),$.push(dB(d0.SHA256_WITH_RSA)),$.push(bz(w.issuer)),$.push(Y7(w.notBefore,w.notAfter)),$.push(bz(w.subject)),$.push(A7(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push($Y(d0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,U7(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push($Y(d0.KEY_USAGE,w.extensions.keyUsage.critical??!0,W7(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push($Y(d0.EXTENDED_KEY_USAGE,!1,j7(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push($Y(d0.SUBJECT_ALT_NAME,!1,J7(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push($Y(d0.SUBJECT_KEY_IDENTIFIER,!1,gB(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(Pz(3,ww(...Y)))}return ww(...$)}function f7(w,$){let Y=M1.createSign("SHA256");Y.update(w);let A=Y.sign($);return ww(w,dB(d0.SHA256_WITH_RSA),mB(A))}function z7(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
|
|
126
126
|
${A.join(`
|
|
127
127
|
`)}
|
|
128
128
|
-----END ${$}-----
|
|
129
129
|
`}function zW(){let w=M1.randomBytes(20);return w[0]=w[0]&127||1,w}function nB(w=2048){let{privateKey:$,publicKey:Y}=M1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function B7(w){let $=w.export({type:"spki",format:"der"});return M1.createHash("sha1").update($).digest()}function lB(w){let $={serialNumber:w.serialNumber||zW(),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:B7(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=Q7($),A=f7(Y,w.signingKey);return{certificate:z7(A,"CERTIFICATE"),certificateDer:A}}function pB(w){return w.export({type:"pkcs8",format:"pem"})}function G7(w){return M1.createPrivateKey(w)}function E7(w){let $=new M1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
|
|
130
130
|
`);for(let J of X){let[U,...j]=J.split("="),W=j.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function BW(w={}){S("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||Hw.DEFAULT_KEY_SIZE;S("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=nB($),X=[{shortName:"C",value:w.countryName||f0.countryName},{shortName:"ST",value:w.stateName||f0.stateName},{shortName:"L",value:w.localityName||f0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=fW({validityYears:w.validityYears||Hw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:j}=lB({serialNumber:zW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:j,privateKey:pB(Y),notBefore:J,notAfter:U}}async function GW(w){if(S("ca","Generating new certificate",w.verbose),S("ca",`Options: ${hX(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=E7(w.rootCA.certificate),Y=G7(w.rootCA.privateKey);S("ca",`Generating ${Hw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=Hw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=nB(A),U=w.commonName||cB(w),j=w.certificateAttributes||[{shortName:"C",value:w.countryName||f0.countryName},{shortName:"ST",value:w.stateName||f0.stateName},{shortName:"L",value:w.localityName||f0.localityName},{shortName:"O",value:w.organizationName||f0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:Q}=fW({validityDays:w.validityDays||Hw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),f=vB(w),z=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},B=w.extKeyUsage||{serverAuth:!0},{certificate:G}=lB({serialNumber:zW(),notBefore:W,notAfter:Q,subject:j,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:B,subjectAltName:f});return{certificate:G,privateKey:pB(X),notBefore:W,notAfter:Q}}function rB(w,$){S(O.STORAGE,`Storing certificate and private key with options: ${hX($)}`,$?.verbose);let{certPath:Y,keyPath:A}=QW({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});S(O.STORAGE,`Certificate path: ${Y}`,$?.verbose),S(O.STORAGE,`Private key path: ${A}`,$?.verbose);let X=sU.dirname(Y);if(!pw.existsSync(X))S(O.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),pw.mkdirSync(X,{recursive:!0});S(O.STORAGE,"Writing certificate file",$?.verbose),pw.writeFileSync(Y,w.certificate);let J=sU.dirname(A);if(!pw.existsSync(J))S(O.STORAGE,`Creating private key directory: ${J}`,$?.verbose),pw.mkdirSync(J,{recursive:!0});return S(O.STORAGE,"Writing private key file",$?.verbose),pw.writeFileSync(A,w.privateKey),S(O.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function tB(w,$){S(O.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=QW({basePath:$?.basePath,caCertPath:$?.caCertPath});S(O.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=sU.dirname(Y);if(!pw.existsSync(A))S(O.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),pw.mkdirSync(A,{recursive:!0});return S(O.STORAGE,"Writing CA certificate file",$?.verbose),pw.writeFileSync(Y,w),S(O.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function _X(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=bB(w);return new K7.X509Certificate($)}function DX(w){return _X(w).fingerprint256.replace(/:/g,"").toUpperCase()}function EW(w){return aB(_X(w).subject)}function F7(w){let $=[],Y=w.split(`
|
|
131
|
-
`);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function aB(w){return F7(w).find(($)=>$.shortName==="CN")?.value||""}function T7(w){let $=[],Y=aB(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 KW(w,$){let Y=_X(w),A=T7(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
|
|
132
|
-
`).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return S(O.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return S(O.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return S(O.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function FW(w,$,Y){S(O.TRUST,`Adding certificate to system trust store with options: ${hX(Y)}`,Y?.verbose),S(O.TRUST,"Storing certificate and private key",Y?.verbose);let A=rB(w,Y);S(O.TRUST,"Storing CA certificate",Y?.verbose);let X=tB($,Y),J=IX.platform();S(O.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=y7[J];if(!U){let j=`Unsupported platform: ${J}`;throw S(O.TRUST,`Error: ${j}`,Y?.verbose),Error(j)}return await U.addCertificate(X,Y),S(O.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var RK,uz=30000,CX,dz="https://acme-staging-v02.api.letsencrypt.org/directory",nz="https://acme-v02.api.letsencrypt.org/directory",WX,LK="1.2.840.10045.2.1",SK="1.2.840.10045.3.1.7",OK="1.2.840.10045.4.3.2",hK="2.5.4.3",_K="1.2.840.113549.1.9.14",DK="2.5.29.17",GX,eU,yF,IF=(w)=>w,VF=(w,$)=>{for(var Y in $)yF(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:CF.bind($,Y)})},LF=(w,$)=>()=>(w&&($=w(w=0)),$),XB,GB,H1,QY,EB,wT,$T,yz,AX,uU,_0,e,YT,Iz,AT,Cz,XT,JT,LU,UT,Vz,Lz,SU,WT,jT,QT,fT,XX,KB,zT,D0,BT,GT,Sz,JX,cU,N0,u,ET,Oz,KT,hz,FT,TT,OU,NT,_z,Dz,qT,hU,HT,RT,MT,yT,IT,UX,FB,CT,VT="0.15.6",e0,NX,UY,vU,mU,qX,gU,dU,WY,nU,lU,B$,TB,NB,qw,rw,qB,HB,LT,OT,RB,HX,JC,I0,m,UC,_T,WC,DT,jC,QC,xz,fC,xT,kT,zC,kz,BC,GC,EC,KC,FC,_U,ZT,TC,Mw,yB,RX,IB,CB,WW,VB,LB,MX,SB,OB,R1,mT,gw,NC,qC,HC,PB,f0,Hw,O,q1,pT,Zz="[redacted]",rT,tT,Rw,d0,H7,R7,M7,y7;var sB=s(()=>{RK=HK(import.meta.url);CX=new XY;WX=class WX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};GX=new YB,eU=new AB,yF=Object.defineProperty;XB={};VF(XB,{withErrorRecovery:()=>WB,tryLoadConfig:()=>aF,loadConfigWithResult:()=>rF,loadConfig:()=>BB,isRetryableError:()=>mF,isConfigNotFoundError:()=>vF,isBunfigError:()=>jB,globalPerformanceMonitor:()=>QY,globalCache:()=>H1,getEnvOrDefault:()=>gF,generateConfigTypes:()=>sF,defaultGeneratedDir:()=>HB,defaultConfigDir:()=>qB,deepMergeWithArrayStrategy:()=>XW,deepMerge:()=>QB,createLibraryConfig:()=>oF,config:()=>tF,bunfigPlugin:()=>eF,applyEnvVarsToConfig:()=>YY,TypeGenerationError:()=>dU,SchemaValidationError:()=>WY,PluginError:()=>lU,PerformanceMonitor:()=>$W,FileSystemError:()=>gU,ErrorFactory:()=>B$,EnvVarError:()=>qX,EnvProcessor:()=>LX,ConfigValidator:()=>JW,ConfigValidationError:()=>vU,ConfigNotFoundError:()=>NX,ConfigMergeError:()=>mU,ConfigLoader:()=>UW,ConfigLoadError:()=>UY,ConfigFileLoader:()=>SX,ConfigCache:()=>wW,CacheUtils:()=>EB,BunfigError:()=>e0,BrowserConfigError:()=>nU,ArrayMergeStrategies:()=>TB});LT=LF(async()=>{GB=import.meta.require,H1=new wW,QY=new $W,EB={createKey:SF,isEquivalent:OF,estimateMemoryUsage:hF},wT=zX(iU.cwd(),"config"),$T=zX(iU.cwd(),"src/generated"),yz=fX.env.CLARITY_LOG_DIR||gK(xF(),"logs"),AX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},uU=await kF(),_0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},e=_0,YT=_0.red,Iz=_0.green,AT=_0.yellow,Cz=_0.blue,XT=_0.magenta,JT=_0.cyan,LU=_0.white,UT=_0.gray,Vz=_0.bgRed,Lz=_0.bgYellow,SU=_0.bold,WT=_0.dim,jT=_0.italic,QT=_0.underline,fT=_0.reset,XX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},KB={debug:"\uD83D\uDD0D",info:Cz("ℹ"),success:Iz("✓"),warning:Lz(LU(SU(" WARN "))),error:Vz(LU(SU(" ERROR ")))},zT=new KX("stacks"),D0=new KX("bunfig",{showTags:!0}),BT=m0(JY.cwd(),"config"),GT=m0(JY.cwd(),"src/generated"),Sz=QX.env.CLARITY_LOG_DIR||vK(bF(),"logs"),JX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},cU=await uF(),N0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=N0,ET=N0.red,Oz=N0.green,KT=N0.yellow,hz=N0.blue,FT=N0.magenta,TT=N0.cyan,OU=N0.white,NT=N0.gray,_z=N0.bgRed,Dz=N0.bgYellow,qT=N0.bgGray,hU=N0.bold,HT=N0.dim,RT=N0.italic,MT=N0.underline,yT=N0.strikethrough,IT=N0.reset,UX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},FB={debug:"\uD83D\uDD0D",info:hz("ℹ"),success:Oz("✓"),warning:Dz(OU(hU(" WARN "))),error:_z(OU(hU(" ERROR ")))},CT=new TX("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}`}},NX=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},UY=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},vU=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},mU=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}},qX=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})}},gU=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}},dU=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WY=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},nU=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})}},lU=class extends e0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B$={configNotFound(w,$,Y){return new NX(w,$,Y)},configLoad(w,$,Y){return new UY(w,$,Y)},configValidation(w,$,Y){return new vU(w,$,Y)},configMerge(w,$,Y,A){return new mU(w,$,Y,A)},envVar(w,$,Y,A){return new qX(w,$,Y,A)},fileSystem(w,$,Y){return new gU(w,$,Y)},typeGeneration(w,$,Y){return new dU(w,$,Y)},schemaValidation(w,$,Y){return new WY(w,$,Y)},browserConfig(w,$,Y,A){return new nU(w,$,Y,A)},plugin(w,$,Y){return new lU(w,$,Y)}},TB={replace:"replace",concat:"concat",smart:"smart"},NB=/^https?:\/\//,qw=new TX("bunfig",{showTags:!0}),rw=new UW,qB=g0(x$.cwd(),"config"),HB=g0(x$.cwd(),"src/generated")});OT=BX.env.CLARITY_LOG_DIR||zF(ST(),"logs"),RB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:OT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},HX={...RB},JC=(async()=>{try{let{loadConfig:w}=await LT().then(()=>XB),$=await w({name:"clarity",alias:"logging",defaultConfig:RB,cwd:BX.cwd()});if($)Object.assign(HX,$)}catch{}return HX})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=I0,UC=I0.red,_T=I0.green,WC=I0.yellow,DT=I0.blue,jC=I0.magenta,QC=I0.cyan,xz=I0.white,fC=I0.gray,xT=I0.bgRed,kT=I0.bgYellow,zC=I0.bgGray,kz=I0.bold,BC=I0.dim,GC=I0.italic,EC=I0.underline,KC=I0.strikethrough,FC=I0.reset,_U={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ZT={debug:"\uD83D\uDD0D",info:DT("ℹ"),success:_T("✓"),warning:kT(xz(kz(" WARN "))),error:xT(xz(kz(" ERROR ")))};TC=new OX("stacks");Mw=class Mw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};yB=class yB extends Mw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};RX=class RX extends Mw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};IB=class IB extends Mw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};CB=class CB extends Mw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};WW=class WW extends Mw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};VB=class VB extends Mw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};LB=class LB extends Mw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};MX=class MX extends Mw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};SB=class SB extends Mw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};OB=class OB extends Mw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};R1={configNotFound(w,$,Y){return new yB(w,$,Y)},configLoad(w,$,Y){return new RX(w,$,Y)},configValidation(w,$,Y){return new IB(w,$,Y)},configMerge(w,$,Y,A){return new CB(w,$,Y,A)},envVar(w,$,Y,A){return new WW(w,$,Y,A)},fileSystem(w,$,Y){return new VB(w,$,Y)},typeGeneration(w,$,Y){return new LB(w,$,Y)},schemaValidation(w,$,Y){return new MX(w,$,Y)},browserConfig(w,$,Y,A){return new SB(w,$,Y,A)},plugin(w,$,Y){return new OB(w,$,Y)}};mT=/^https?:\/\//;gw=new OX("bunfig",{showTags:!0});NC=new ZB;qC=fw(VX.cwd(),"config"),HC=fw(VX.cwd(),"src/generated"),PB={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:BU.join(zU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:BU.join(zU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:BU.join(zU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},f0=PB,Hw={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"},O={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},q1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};pT=lT(dT);rT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),tT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Rw={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},d0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};H7={platform:"darwin",async addCertificate(w,$){if(await q7(w,$?.verbose)){S(O.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),q1.success("Certificate is already trusted in system keychain");return}S(O.TRUST,"Adding certificate to macOS keychain",$?.verbose),await z$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(O.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await z$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),S(O.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw S(O.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},R7={platform:"win32",async addCertificate(w,$){S(O.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await z$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(O.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await z$(`certutil -delstore -enterprise Root "${A}"`),S(O.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw S(O.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},M7={platform:"linux",async addCertificate(w,$){S(O.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=IX.homedir(),A=Hw.LINUX_CERT_DB_FILENAME,X=Hw.LINUX_TRUST_ARGS;S(O.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=tU(Y,A);if(J.length===0){q1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){S(O.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{S(O.TRUST,`Attempting to delete existing cert for ${f0.commonName}`,$?.verbose),await z$(`certutil -d sql:${U} -D -n ${f0.commonName}`)}catch(j){S(O.TRUST,`Warning: Error deleting existing cert: ${j}`,$?.verbose),console.warn(`Error deleting existing cert: ${j}`)}S(O.TRUST,`Adding new certificate to ${U}`,$?.verbose),await z$(`certutil -d sql:${U} -A -t ${X} -n ${f0.commonName} -i ${w}`),q1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(O.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=IX.homedir(),J=Hw.LINUX_CERT_DB_FILENAME;S(O.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=tU(X,J);if(U.length===0){q1.warn("No certificate databases found. Cannot remove certificate.");return}for(let j of U){S(O.TRUST,`Processing certificate database in ${j}`,$?.verbose);try{await z$(`certutil -d sql:${j} -D -n "${A}"`),q1.info(`Cert removed from ${j}`)}catch(W){S(O.TRUST,`Error removing cert from ${j}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${j}: ${W}`)}}}},y7={darwin:H7,win32:R7,linux:M7}});var xX=s(()=>{sB()});function k$(w){try{return DX(w)}catch{return null}}function TW(w){try{return EW(w)||null}catch{return null}}function NW(w,$){try{return $.every((Y)=>KW(w,Y))}catch{return!1}}var kX=s(()=>{xX()});import{existsSync as oB,statSync as eB}from"fs";import{existsSync as iW,mkdirSync as h7,readdirSync as _7,writeFileSync as D7}from"fs";import{homedir as y1}from"os";import{dirname as w9,resolve as l0}from"path";import Z$ from"process";import{join as x7,relative as k7,resolve as $9}from"path";import sX from"process";import{existsSync as i9,mkdirSync as IV,readdirSync as CV,writeFileSync as VV}from"fs";import{homedir as qW}from"os";import{dirname as OV,resolve as n0}from"path";import zY from"process";import{join as Z7,relative as P7,resolve as Y9}from"path";import oX from"process";import{existsSync as b9,mkdirSync as kV,readdirSync as ZV,writeFileSync as PV}from"fs";import{dirname as bV,resolve as eX}from"path";import bW from"process";import{Buffer as E$}from"buffer";import{createCipheriv as i7,createDecipheriv as b7,randomBytes as HW}from"crypto";import{closeSync as RW,createReadStream as A9,createWriteStream as u7,existsSync as MW,fsyncSync as X9,openSync as J9,writeFileSync as c7}from"fs";import{access as v7,constants as U9,mkdir as m7,readdir as ZX,rename as W9,stat as I1,unlink as PX,writeFile as yW}from"fs/promises";import{join as C1}from"path";import x0 from"process";import{pipeline as g7}from"stream/promises";import{createGzip as j9}from"zlib";import V1 from"process";import sw from"process";import{Buffer as tw}from"buffer";import{createCipheriv as d7,createDecipheriv as n7,randomBytes as IW}from"crypto";import{closeSync as CW,createReadStream as Q9,createWriteStream as l7,existsSync as iX,fsyncSync as f9,openSync as z9,writeFileSync as p7}from"fs";import{access as r7,constants as B9,mkdir as t7,readdir as bX,rename as G9,stat as L1,unlink as uX,writeFile as VW}from"fs/promises";import{isAbsolute as a7,join as S1,resolve as s7}from"path";import Z from"process";import{pipeline as o7}from"stream/promises";import{createGzip as E9}from"zlib";import O1 from"process";import ow from"process";import cX from"process";import{existsSync as vX}from"fs";import{resolve as LW}from"path";import{existsSync as e7}from"fs";import{existsSync as wN,readdirSync as $N}from"fs";import{extname as SW,resolve as K9}from"path";import YN from"process";import{join as Aq,relative as Xq,resolve as L9}from"path";import U8 from"process";import{Buffer as aw}from"buffer";import{createCipheriv as Wq,createDecipheriv as jq,randomBytes as xW}from"crypto";import{closeSync as kW,createReadStream as S9,createWriteStream as Qq,existsSync as gX,fsyncSync as O9,openSync as h9,writeFileSync as fq}from"fs";import{access as zq,constants as _9,mkdir as Bq,readdir as dX,rename as D9,stat as h1,unlink as nX,writeFile as ZW}from"fs/promises";import{isAbsolute as Gq,join as _1,resolve as Eq}from"path";import P from"process";import{pipeline as Kq}from"stream/promises";import{createGzip as x9}from"zlib";import D1 from"process";import ew from"process";function L7(w,$){this[w]=V7.bind(null,$)}class rW{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(!oB(w))return!0;return eB(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=oB(Y)?eB(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 tW{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 AN(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function XN(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function JN(w){return w.getStats().size*2}function aW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&X0($[0])&&"id"in $[0]&&$[0].id===3&&X0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(X0($)&&X0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(X0(w)&&"arr"in w&&Array.isArray(w.arr)&&X0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&X0($[0])&&X0(w[0])){let A=[...$];for(let X of w)if(X0(X)&&"name"in X){if(!A.find((U)=>X0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(X0(X)&&"path"in X){if(!A.find((U)=>X0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>w8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!X0($)||!X0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(X0(X)&&X0(Y[A]))Y[A]=aW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&X0(X[0])&&X0(Y[A][0])){let J=[...X];for(let U of Y[A])if(X0(U)&&"name"in U){if(!J.find((W)=>X0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(X0(U)&&"path"in U){if(!J.find((W)=>X0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>w8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function w8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!w8(w[Y],$[Y]))return!1;return!0}if(X0(w)&&X0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!w8(w[X],$[X]))return!1}return!0}return!1}function X0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function UN(w,$){if(!b9(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 aW($,A)}catch{return null}}catch{return null}}async function WN({name:w="",cwd:$,defaultConfig:Y}){let A=$||bW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=eX(A,`${U}${j}`),Q=await UN(W,Y);if(Q!==null)return Q}try{let U=eX(A,"package.json");if(b9(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return aW(Y,W)}catch{}}}catch{}return Y}function jN(w,$={}){let Y=oX.cwd();while(Y.includes("storage"))Y=Y9(Y,"..");let A=Y9(Y,w||"");if($?.relative)return P7(oX.cwd(),A);return A}async function QN(){try{let w=await WN({name:"clarity",defaultConfig:pX,cwd:oX.cwd(),endpoint:"",headers:{}});return{...pX,...w}}catch{return pX}}function j0(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fN(){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 u9{async format(w){let $=await fN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid: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 $8{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={...cW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new u9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...rX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...rX};return{...rX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:cW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await v7(this.config.logDirectory,U9.F_OK|U9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await m7(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(!MW(this.currentLogFile))await yW(this.currentLogFile,"",{mode:420});if(X=J9(this.currentLogFile,"a",420),c7(X,W,{flag:"a"}),X9(X),X!==void 0)RW(X),X=void 0;if((await I1(this.currentLogFile)).size===0){if(await yW(this.currentLogFile,W,{flag:"w",mode:420}),(await I1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{RW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return C1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return C1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return C1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(j0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return HW(16).toString("hex")}generateKey(){return HW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=HW(16),A=i7("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=j9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(E$.from(E$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(j0())return;let w=await I1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await ZX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await I1(Y).catch(()=>null))try{if(await W9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await PX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await yW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await I1(Y).catch(()=>null))await W9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await ZX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await PX(C1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=A9(w),A=u7($),X=j9();await g7(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()})),MW(this.currentLogFile))try{let w=J9(this.currentLogFile,"r+");X9(w),RW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!j0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await ZX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await PX(C1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?w0.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${w0.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!j0()){let Q=t9[w],f=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:w0.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:w0.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
|
|
131
|
+
`);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function aB(w){return F7(w).find(($)=>$.shortName==="CN")?.value||""}function T7(w){let $=[],Y=aB(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 KW(w,$){let Y=_X(w),A=T7(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 N7(w,$){if(IX.platform()!=="darwin")return!1;try{let Y=DX(w);if(!Y)return S(O.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(q7("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
132
|
+
`).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return S(O.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return S(O.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return S(O.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function FW(w,$,Y){S(O.TRUST,`Adding certificate to system trust store with options: ${hX(Y)}`,Y?.verbose),S(O.TRUST,"Storing certificate and private key",Y?.verbose);let A=rB(w,Y);S(O.TRUST,"Storing CA certificate",Y?.verbose);let X=tB($,Y),J=IX.platform();S(O.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=y7[J];if(!U){let j=`Unsupported platform: ${J}`;throw S(O.TRUST,`Error: ${j}`,Y?.verbose),Error(j)}return await U.addCertificate(X,Y),S(O.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var RK,uz=30000,CX,dz="https://acme-staging-v02.api.letsencrypt.org/directory",nz="https://acme-v02.api.letsencrypt.org/directory",WX,LK="1.2.840.10045.2.1",SK="1.2.840.10045.3.1.7",OK="1.2.840.10045.4.3.2",hK="2.5.4.3",_K="1.2.840.113549.1.9.14",DK="2.5.29.17",GX,eU,yF,IF=(w)=>w,VF=(w,$)=>{for(var Y in $)yF(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:CF.bind($,Y)})},LF=(w,$)=>()=>(w&&($=w(w=0)),$),XB,GB,H1,QY,EB,wT,$T,yz,AX,uU,_0,e,YT,Iz,AT,Cz,XT,JT,LU,UT,Vz,Lz,SU,WT,jT,QT,fT,XX,KB,zT,D0,BT,GT,Sz,JX,cU,q0,u,ET,Oz,KT,hz,FT,TT,OU,qT,_z,Dz,NT,hU,HT,RT,MT,yT,IT,UX,FB,CT,VT="0.15.6",e0,qX,UY,vU,mU,NX,gU,dU,WY,nU,lU,B$,TB,qB,Nw,rw,NB,HB,LT,OT,RB,HX,JC,I0,m,UC,_T,WC,DT,jC,QC,xz,fC,xT,kT,zC,kz,BC,GC,EC,KC,FC,_U,ZT,TC,Mw,yB,RX,IB,CB,WW,VB,LB,MX,SB,OB,R1,mT,gw,qC,NC,HC,PB,f0,Hw,O,N1,pT,Zz="[redacted]",rT,tT,Rw,d0,H7,R7,M7,y7;var sB=s(()=>{RK=HK(import.meta.url);CX=new XY;WX=class WX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};GX=new YB,eU=new AB,yF=Object.defineProperty;XB={};VF(XB,{withErrorRecovery:()=>WB,tryLoadConfig:()=>aF,loadConfigWithResult:()=>rF,loadConfig:()=>BB,isRetryableError:()=>mF,isConfigNotFoundError:()=>vF,isBunfigError:()=>jB,globalPerformanceMonitor:()=>QY,globalCache:()=>H1,getEnvOrDefault:()=>gF,generateConfigTypes:()=>sF,defaultGeneratedDir:()=>HB,defaultConfigDir:()=>NB,deepMergeWithArrayStrategy:()=>XW,deepMerge:()=>QB,createLibraryConfig:()=>oF,config:()=>tF,bunfigPlugin:()=>eF,applyEnvVarsToConfig:()=>YY,TypeGenerationError:()=>dU,SchemaValidationError:()=>WY,PluginError:()=>lU,PerformanceMonitor:()=>$W,FileSystemError:()=>gU,ErrorFactory:()=>B$,EnvVarError:()=>NX,EnvProcessor:()=>LX,ConfigValidator:()=>JW,ConfigValidationError:()=>vU,ConfigNotFoundError:()=>qX,ConfigMergeError:()=>mU,ConfigLoader:()=>UW,ConfigLoadError:()=>UY,ConfigFileLoader:()=>SX,ConfigCache:()=>wW,CacheUtils:()=>EB,BunfigError:()=>e0,BrowserConfigError:()=>nU,ArrayMergeStrategies:()=>TB});LT=LF(async()=>{GB=import.meta.require,H1=new wW,QY=new $W,EB={createKey:SF,isEquivalent:OF,estimateMemoryUsage:hF},wT=zX(iU.cwd(),"config"),$T=zX(iU.cwd(),"src/generated"),yz=fX.env.CLARITY_LOG_DIR||gK(xF(),"logs"),AX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},uU=await kF(),_0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},e=_0,YT=_0.red,Iz=_0.green,AT=_0.yellow,Cz=_0.blue,XT=_0.magenta,JT=_0.cyan,LU=_0.white,UT=_0.gray,Vz=_0.bgRed,Lz=_0.bgYellow,SU=_0.bold,WT=_0.dim,jT=_0.italic,QT=_0.underline,fT=_0.reset,XX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},KB={debug:"\uD83D\uDD0D",info:Cz("ℹ"),success:Iz("✓"),warning:Lz(LU(SU(" WARN "))),error:Vz(LU(SU(" ERROR ")))},zT=new KX("stacks"),D0=new KX("bunfig",{showTags:!0}),BT=m0(JY.cwd(),"config"),GT=m0(JY.cwd(),"src/generated"),Sz=QX.env.CLARITY_LOG_DIR||vK(bF(),"logs"),JX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},cU=await uF(),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,ET=q0.red,Oz=q0.green,KT=q0.yellow,hz=q0.blue,FT=q0.magenta,TT=q0.cyan,OU=q0.white,qT=q0.gray,_z=q0.bgRed,Dz=q0.bgYellow,NT=q0.bgGray,hU=q0.bold,HT=q0.dim,RT=q0.italic,MT=q0.underline,yT=q0.strikethrough,IT=q0.reset,UX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},FB={debug:"\uD83D\uDD0D",info:hz("ℹ"),success:Oz("✓"),warning:Dz(OU(hU(" WARN "))),error:_z(OU(hU(" ERROR ")))},CT=new TX("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}`}},qX=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},UY=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},vU=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},mU=class extends e0{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},NX=class extends e0{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},gU=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}},dU=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WY=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},nU=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})}},lU=class extends e0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B$={configNotFound(w,$,Y){return new qX(w,$,Y)},configLoad(w,$,Y){return new UY(w,$,Y)},configValidation(w,$,Y){return new vU(w,$,Y)},configMerge(w,$,Y,A){return new mU(w,$,Y,A)},envVar(w,$,Y,A){return new NX(w,$,Y,A)},fileSystem(w,$,Y){return new gU(w,$,Y)},typeGeneration(w,$,Y){return new dU(w,$,Y)},schemaValidation(w,$,Y){return new WY(w,$,Y)},browserConfig(w,$,Y,A){return new nU(w,$,Y,A)},plugin(w,$,Y){return new lU(w,$,Y)}},TB={replace:"replace",concat:"concat",smart:"smart"},qB=/^https?:\/\//,Nw=new TX("bunfig",{showTags:!0}),rw=new UW,NB=g0(x$.cwd(),"config"),HB=g0(x$.cwd(),"src/generated")});OT=BX.env.CLARITY_LOG_DIR||zF(ST(),"logs"),RB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:OT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},HX={...RB},JC=(async()=>{try{let{loadConfig:w}=await LT().then(()=>XB),$=await w({name:"clarity",alias:"logging",defaultConfig:RB,cwd:BX.cwd()});if($)Object.assign(HX,$)}catch{}return HX})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=I0,UC=I0.red,_T=I0.green,WC=I0.yellow,DT=I0.blue,jC=I0.magenta,QC=I0.cyan,xz=I0.white,fC=I0.gray,xT=I0.bgRed,kT=I0.bgYellow,zC=I0.bgGray,kz=I0.bold,BC=I0.dim,GC=I0.italic,EC=I0.underline,KC=I0.strikethrough,FC=I0.reset,_U={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ZT={debug:"\uD83D\uDD0D",info:DT("ℹ"),success:_T("✓"),warning:kT(xz(kz(" WARN "))),error:xT(xz(kz(" ERROR ")))};TC=new OX("stacks");Mw=class Mw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};yB=class yB extends Mw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};RX=class RX extends Mw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};IB=class IB extends Mw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};CB=class CB extends Mw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};WW=class WW extends Mw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};VB=class VB extends Mw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};LB=class LB extends Mw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};MX=class MX extends Mw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};SB=class SB extends Mw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};OB=class OB extends Mw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};R1={configNotFound(w,$,Y){return new yB(w,$,Y)},configLoad(w,$,Y){return new RX(w,$,Y)},configValidation(w,$,Y){return new IB(w,$,Y)},configMerge(w,$,Y,A){return new CB(w,$,Y,A)},envVar(w,$,Y,A){return new WW(w,$,Y,A)},fileSystem(w,$,Y){return new VB(w,$,Y)},typeGeneration(w,$,Y){return new LB(w,$,Y)},schemaValidation(w,$,Y){return new MX(w,$,Y)},browserConfig(w,$,Y,A){return new SB(w,$,Y,A)},plugin(w,$,Y){return new OB(w,$,Y)}};mT=/^https?:\/\//;gw=new OX("bunfig",{showTags:!0});qC=new ZB;NC=fw(VX.cwd(),"config"),HC=fw(VX.cwd(),"src/generated"),PB={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:BU.join(zU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:BU.join(zU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:BU.join(zU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},f0=PB,Hw={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"},O={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},N1={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)};pT=lT(dT);rT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),tT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Rw={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},d0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};H7={platform:"darwin",async addCertificate(w,$){if(await N7(w,$?.verbose)){S(O.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),N1.success("Certificate is already trusted in system keychain");return}S(O.TRUST,"Adding certificate to macOS keychain",$?.verbose),await z$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(O.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await z$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),S(O.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw S(O.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},R7={platform:"win32",async addCertificate(w,$){S(O.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await z$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(O.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await z$(`certutil -delstore -enterprise Root "${A}"`),S(O.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw S(O.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},M7={platform:"linux",async addCertificate(w,$){S(O.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=IX.homedir(),A=Hw.LINUX_CERT_DB_FILENAME,X=Hw.LINUX_TRUST_ARGS;S(O.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=tU(Y,A);if(J.length===0){N1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){S(O.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{S(O.TRUST,`Attempting to delete existing cert for ${f0.commonName}`,$?.verbose),await z$(`certutil -d sql:${U} -D -n ${f0.commonName}`)}catch(j){S(O.TRUST,`Warning: Error deleting existing cert: ${j}`,$?.verbose),console.warn(`Error deleting existing cert: ${j}`)}S(O.TRUST,`Adding new certificate to ${U}`,$?.verbose),await z$(`certutil -d sql:${U} -A -t ${X} -n ${f0.commonName} -i ${w}`),N1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(O.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=IX.homedir(),J=Hw.LINUX_CERT_DB_FILENAME;S(O.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=tU(X,J);if(U.length===0){N1.warn("No certificate databases found. Cannot remove certificate.");return}for(let j of U){S(O.TRUST,`Processing certificate database in ${j}`,$?.verbose);try{await z$(`certutil -d sql:${j} -D -n "${A}"`),N1.info(`Cert removed from ${j}`)}catch(W){S(O.TRUST,`Error removing cert from ${j}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${j}: ${W}`)}}}},y7={darwin:H7,win32:R7,linux:M7}});var xX=s(()=>{sB()});function k$(w){try{return DX(w)}catch{return null}}function TW(w){try{return EW(w)||null}catch{return null}}function qW(w,$){try{return $.every((Y)=>KW(w,Y))}catch{return!1}}var kX=s(()=>{xX()});import{existsSync as oB,statSync as eB}from"fs";import{existsSync as iW,mkdirSync as h7,readdirSync as _7,writeFileSync as D7}from"fs";import{homedir as y1}from"os";import{dirname as w9,resolve as l0}from"path";import Z$ from"process";import{join as x7,relative as k7,resolve as $9}from"path";import sX from"process";import{existsSync as i9,mkdirSync as IV,readdirSync as CV,writeFileSync as VV}from"fs";import{homedir as NW}from"os";import{dirname as OV,resolve as n0}from"path";import zY from"process";import{join as Z7,relative as P7,resolve as Y9}from"path";import oX from"process";import{existsSync as b9,mkdirSync as kV,readdirSync as ZV,writeFileSync as PV}from"fs";import{dirname as bV,resolve as eX}from"path";import bW from"process";import{Buffer as E$}from"buffer";import{createCipheriv as i7,createDecipheriv as b7,randomBytes as HW}from"crypto";import{closeSync as RW,createReadStream as A9,createWriteStream as u7,existsSync as MW,fsyncSync as X9,openSync as J9,writeFileSync as c7}from"fs";import{access as v7,constants as U9,mkdir as m7,readdir as ZX,rename as W9,stat as I1,unlink as PX,writeFile as yW}from"fs/promises";import{join as C1}from"path";import x0 from"process";import{pipeline as g7}from"stream/promises";import{createGzip as j9}from"zlib";import V1 from"process";import sw from"process";import{Buffer as tw}from"buffer";import{createCipheriv as d7,createDecipheriv as n7,randomBytes as IW}from"crypto";import{closeSync as CW,createReadStream as Q9,createWriteStream as l7,existsSync as iX,fsyncSync as f9,openSync as z9,writeFileSync as p7}from"fs";import{access as r7,constants as B9,mkdir as t7,readdir as bX,rename as G9,stat as L1,unlink as uX,writeFile as VW}from"fs/promises";import{isAbsolute as a7,join as S1,resolve as s7}from"path";import Z from"process";import{pipeline as o7}from"stream/promises";import{createGzip as E9}from"zlib";import O1 from"process";import ow from"process";import cX from"process";import{existsSync as vX}from"fs";import{resolve as LW}from"path";import{existsSync as e7}from"fs";import{existsSync as wq,readdirSync as $q}from"fs";import{extname as SW,resolve as K9}from"path";import Yq from"process";import{join as AN,relative as XN,resolve as L9}from"path";import U8 from"process";import{Buffer as aw}from"buffer";import{createCipheriv as WN,createDecipheriv as jN,randomBytes as xW}from"crypto";import{closeSync as kW,createReadStream as S9,createWriteStream as QN,existsSync as gX,fsyncSync as O9,openSync as h9,writeFileSync as fN}from"fs";import{access as zN,constants as _9,mkdir as BN,readdir as dX,rename as D9,stat as h1,unlink as nX,writeFile as ZW}from"fs/promises";import{isAbsolute as GN,join as _1,resolve as EN}from"path";import P from"process";import{pipeline as KN}from"stream/promises";import{createGzip as x9}from"zlib";import D1 from"process";import ew from"process";function L7(w,$){this[w]=V7.bind(null,$)}class rW{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(!oB(w))return!0;return eB(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=oB(Y)?eB(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 tW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function Aq(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function Xq(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function Jq(w){return w.getStats().size*2}function aW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&X0($[0])&&"id"in $[0]&&$[0].id===3&&X0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(X0($)&&X0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(X0(w)&&"arr"in w&&Array.isArray(w.arr)&&X0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&X0($[0])&&X0(w[0])){let A=[...$];for(let X of w)if(X0(X)&&"name"in X){if(!A.find((U)=>X0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(X0(X)&&"path"in X){if(!A.find((U)=>X0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>w8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!X0($)||!X0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(X0(X)&&X0(Y[A]))Y[A]=aW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&X0(X[0])&&X0(Y[A][0])){let J=[...X];for(let U of Y[A])if(X0(U)&&"name"in U){if(!J.find((W)=>X0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(X0(U)&&"path"in U){if(!J.find((W)=>X0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>w8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function w8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!w8(w[Y],$[Y]))return!1;return!0}if(X0(w)&&X0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!w8(w[X],$[X]))return!1}return!0}return!1}function X0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function Uq(w,$){if(!b9(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 aW($,A)}catch{return null}}catch{return null}}async function Wq({name:w="",cwd:$,defaultConfig:Y}){let A=$||bW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=eX(A,`${U}${j}`),Q=await Uq(W,Y);if(Q!==null)return Q}try{let U=eX(A,"package.json");if(b9(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return aW(Y,W)}catch{}}}catch{}return Y}function jq(w,$={}){let Y=oX.cwd();while(Y.includes("storage"))Y=Y9(Y,"..");let A=Y9(Y,w||"");if($?.relative)return P7(oX.cwd(),A);return A}async function Qq(){try{let w=await Wq({name:"clarity",defaultConfig:pX,cwd:oX.cwd(),endpoint:"",headers:{}});return{...pX,...w}}catch{return pX}}function j0(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fq(){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 u9{async format(w){let $=await fq(),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 $8{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={...cW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new u9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...rX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...rX};return{...rX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:cW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await v7(this.config.logDirectory,U9.F_OK|U9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await m7(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(!MW(this.currentLogFile))await yW(this.currentLogFile,"",{mode:420});if(X=J9(this.currentLogFile,"a",420),c7(X,W,{flag:"a"}),X9(X),X!==void 0)RW(X),X=void 0;if((await I1(this.currentLogFile)).size===0){if(await yW(this.currentLogFile,W,{flag:"w",mode:420}),(await I1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{RW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return C1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return C1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return C1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(j0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return HW(16).toString("hex")}generateKey(){return HW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=HW(16),A=i7("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=j9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(E$.from(E$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(j0())return;let w=await I1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await ZX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await I1(Y).catch(()=>null))try{if(await W9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await PX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await yW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await I1(Y).catch(()=>null))await W9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await ZX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await PX(C1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=A9(w),A=u7($),X=j9();await g7(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()})),MW(this.currentLogFile))try{let w=J9(this.currentLogFile,"r+");X9(w),RW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!j0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await ZX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await PX(C1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?w0.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${w0.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!j0()){let Q=t9[w],f=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:w0.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:w0.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
|
|
133
133
|
`);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:w0.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!j0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
|
|
134
134
|
`;if(j)W+=`${j}
|
|
135
135
|
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!j0()){let Y=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:w0.blue("◐"),tag:Y,message:`${w0.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
|
|
@@ -137,7 +137,7 @@ ${A.join(`
|
|
|
137
137
|
`),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:w0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(W),showTimestamp:!1}))}else if(!j0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
|
|
138
138
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(j0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${w0.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x0.stdin.removeListener("data",Y);try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!1)}catch{}x0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!0)}catch{}x0.stdin.resume(),x0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!j0()){let U=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",j=w0.blue("◐");console.error(`${j} ${U} ${w0.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
139
139
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||j0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;x0.stdout.write(`${"\r".padEnd(x0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=w0.green("━".repeat(A)),U=w0.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?w0.green("✓"):w0.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${w0.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=x0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,x0.stdout.write(w.lastRenderedLine),$)x0.stdout.write(`
|
|
140
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(j0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await ZX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=C1(this.config.logDirectory,A);if(w.before)try{if((await I1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await PX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function lX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&a($[0])&&"id"in $[0]&&$[0].id===3&&a($[1])&&"id"in $[1]&&$[1].id===4)return $;if(a($)&&a(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(a(w)&&"arr"in w&&Array.isArray(w.arr)&&a($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&a($[0])&&a(w[0])){let A=[...$];for(let X of w)if(a(X)&&"name"in X){if(!A.find((U)=>a(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(a(X)&&"path"in X){if(!A.find((U)=>a(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>Y8(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(!a($)||!a(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(a(X)&&a(Y[A]))Y[A]=lX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&a(X[0])&&a(Y[A][0])){let J=[...X];for(let U of Y[A])if(a(U)&&"name"in U){if(!J.find((W)=>a(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(a(U)&&"path"in U){if(!J.find((W)=>a(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>Y8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function sW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:lX(w,$);if(Array.isArray(w))return Y==="replace"?$:lX(w,$);if(!a($)||!a(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]=lX(U,J);else if(a(J)&&a(U))A[X]=sW(U,J,Y);else A[X]=J}return A}function Y8(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(!Y8(w[Y],$[Y]))return!1;return!0}if(a(w)&&a($)){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(!Y8(w[X],$[X]))return!1}return!0}return!1}function a(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function mX(w,$,Y="replace"){if(!i9(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 sW($,X,Y)}catch{return null}}catch{return null}}function zN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=zY.env[G]||zY.env[T];if(K!==void 0){if(Y)Z0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function BN({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?zN(w,X,J):X,Q=Y||zY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,n0(Q,"config"),n0(Q,".config"),A?n0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)Z0.info(`Searching for configuration in: ${F}`);let R=[n0(Q,"config"),n0(Q,".config")].concat(A?[n0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let V of R)for(let L of f){let q=n0(F,`${V}${L}`),C=await mX(q,W,j);if(C!==null){if(J)Z0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let F=n0(qW(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)Z0.info(`Checking user config directory: ${F}`);for(let R of N)for(let V of f){let L=n0(F,`${R}${V}`),q=await mX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let F=n0(qW(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=n0(F,`${R}${V}`),q=await mX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let F=qW(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=n0(F,`${R}${V}`),q=await mX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let F=n0(Q,"package.json");if(i9(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)Z0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)Z0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return sW(W,R,j)}catch(V){if(J)Z0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)Z0.warn("Failed to load package.json:",F)}if(J)Z0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function GN(w,$={}){let Y=sX.cwd();while(Y.includes("storage"))Y=$9(Y,"..");let A=$9(Y,w||"");if($?.relative)return k7(sX.cwd(),A);return A}async function EN(){try{let w=await BN({name:"clarity",alias:"logging",defaultConfig:tX,cwd:sX.cwd()});return{...tX,...w||{}}}catch{return tX}}function H0(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function KN(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ow<"u"){let w=ow.type;if(w==="renderer"||w==="worker")return!1;return!!(ow.versions&&(ow.versions.node||ow.versions.bun))}return!1}class c9{async format(w){let $=await KN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:O1.pid,hostname:$(),environment:O1.env.NODE_ENV||"development",platform:O1.platform,version:O1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:O1.env.NODE_ENV||O1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class A8{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={...vW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new c9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...aX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...aX};return{...aX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:vW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await r7(this.config.logDirectory,B9.F_OK|B9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await t7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:tw.from(w);try{if(!iX(this.currentLogFile))await VW(this.currentLogFile,"",{mode:420});if(X=z9(this.currentLogFile,"a",420),p7(X,W,{flag:"a"}),f9(X),X!==void 0)CW(X),X=void 0;if((await L1(this.currentLogFile)).size===0){if(await VW(this.currentLogFile,W,{flag:"w",mode:420}),(await L1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{CW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return S1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return S1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return S1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return IW(16).toString("hex")}generateKey(){return IW(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=IW(16),A=d7("aes-256-gcm",$,Y),X=tw.isBuffer(w)?w:tw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=tw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=E9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(tw.from(tw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await L1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await bX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await L1(Y).catch(()=>null))try{if(await G9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await uX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await VW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await L1(Y).catch(()=>null))await G9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await bX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await uX(S1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=Q9(w),A=l7($),X=E9();await o7(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()})),iX(this.currentLogFile))try{let w=z9(this.currentLogFile,"r+");f9(w),CW(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 bX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await uX(S1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof Z.env.NO_COLOR<"u",$=Z.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=Z.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${c.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=Z.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(a7($)||$.startsWith("./")||$.startsWith("../"))$=s7($);else return null;return iX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":a9[w],B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
140
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(j0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await ZX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=C1(this.config.logDirectory,A);if(w.before)try{if((await I1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await PX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function lX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&a($[0])&&"id"in $[0]&&$[0].id===3&&a($[1])&&"id"in $[1]&&$[1].id===4)return $;if(a($)&&a(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(a(w)&&"arr"in w&&Array.isArray(w.arr)&&a($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&a($[0])&&a(w[0])){let A=[...$];for(let X of w)if(a(X)&&"name"in X){if(!A.find((U)=>a(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(a(X)&&"path"in X){if(!A.find((U)=>a(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>Y8(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(!a($)||!a(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(a(X)&&a(Y[A]))Y[A]=lX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&a(X[0])&&a(Y[A][0])){let J=[...X];for(let U of Y[A])if(a(U)&&"name"in U){if(!J.find((W)=>a(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(a(U)&&"path"in U){if(!J.find((W)=>a(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>Y8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function sW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:lX(w,$);if(Array.isArray(w))return Y==="replace"?$:lX(w,$);if(!a($)||!a(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]=lX(U,J);else if(a(J)&&a(U))A[X]=sW(U,J,Y);else A[X]=J}return A}function Y8(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(!Y8(w[Y],$[Y]))return!1;return!0}if(a(w)&&a($)){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(!Y8(w[X],$[X]))return!1}return!0}return!1}function a(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function mX(w,$,Y="replace"){if(!i9(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 sW($,X,Y)}catch{return null}}catch{return null}}function zq(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=zY.env[G]||zY.env[T];if(K!==void 0){if(Y)Z0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((q)=>q.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function Bq({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?zq(w,X,J):X,Q=Y||zY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,n0(Q,"config"),n0(Q,".config"),A?n0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)Z0.info(`Searching for configuration in: ${F}`);let R=[n0(Q,"config"),n0(Q,".config")].concat(A?[n0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let V of R)for(let L of f){let N=n0(F,`${V}${L}`),C=await mX(N,W,j);if(C!==null){if(J)Z0.success(`Configuration loaded from: ${N}`);return C}}}if(w){let F=n0(NW(),".config",w),q=["config",`${w}.config`];if($)q.push(`${$}.config`);if(J)Z0.info(`Checking user config directory: ${F}`);for(let R of q)for(let V of f){let L=n0(F,`${R}${V}`),N=await mX(L,W,j);if(N!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${L}`);return N}}}if(w){let F=n0(NW(),".config"),q=[`.${w}.config`];if($)q.push(`.${$}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of q)for(let V of f){let L=n0(F,`${R}${V}`),N=await mX(L,W,j);if(N!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${L}`);return N}}}if(w){let F=NW(),q=[`.${w}.config`,`.${w}`];if($)q.push(`.${$}.config`),q.push(`.${$}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of q)for(let V of f){let L=n0(F,`${R}${V}`),N=await mX(L,W,j);if(N!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${L}`);return N}}}try{let F=n0(Q,"package.json");if(i9(F)){let q=await import(F),R=q[w];if(!R&&$){if(R=q[$],R&&J)Z0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)Z0.success(`Configuration loaded from package.json: ${R===q[w]?w:$}`);return sW(W,R,j)}catch(V){if(J)Z0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)Z0.warn("Failed to load package.json:",F)}if(J)Z0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function Gq(w,$={}){let Y=sX.cwd();while(Y.includes("storage"))Y=$9(Y,"..");let A=$9(Y,w||"");if($?.relative)return k7(sX.cwd(),A);return A}async function Eq(){try{let w=await Bq({name:"clarity",alias:"logging",defaultConfig:tX,cwd:sX.cwd()});return{...tX,...w||{}}}catch{return tX}}function H0(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Kq(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ow<"u"){let w=ow.type;if(w==="renderer"||w==="worker")return!1;return!!(ow.versions&&(ow.versions.node||ow.versions.bun))}return!1}class c9{async format(w){let $=await Kq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:O1.pid,hostname:$(),environment:O1.env.NODE_ENV||"development",platform:O1.platform,version:O1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:O1.env.NODE_ENV||O1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class A8{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={...vW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new c9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...aX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...aX};return{...aX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:vW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await r7(this.config.logDirectory,B9.F_OK|B9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await t7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:tw.from(w);try{if(!iX(this.currentLogFile))await VW(this.currentLogFile,"",{mode:420});if(X=z9(this.currentLogFile,"a",420),p7(X,W,{flag:"a"}),f9(X),X!==void 0)CW(X),X=void 0;if((await L1(this.currentLogFile)).size===0){if(await VW(this.currentLogFile,W,{flag:"w",mode:420}),(await L1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{CW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return S1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return S1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return S1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return IW(16).toString("hex")}generateKey(){return IW(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=IW(16),A=d7("aes-256-gcm",$,Y),X=tw.isBuffer(w)?w:tw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=tw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=E9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(tw.from(tw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await L1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await bX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await L1(Y).catch(()=>null))try{if(await G9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await uX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await VW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await L1(Y).catch(()=>null))await G9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await bX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await uX(S1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=Q9(w),A=l7($),X=E9();await o7(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()})),iX(this.currentLogFile))try{let w=z9(this.currentLogFile,"r+");f9(w),CW(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 bX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await uX(S1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof Z.env.NO_COLOR<"u",$=Z.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=Z.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${c.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=Z.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(a7($)||$.startsWith("./")||$.startsWith("../"))$=s7($);else return null;return iX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":a9[w],B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
141
141
|
`);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
|
|
142
142
|
`;if(j)f+=`${j}
|
|
143
143
|
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!H0()&&Z.stdout.isTTY)Z.stdout.write(`
|
|
@@ -146,7 +146,7 @@ ${A.join(`
|
|
|
146
146
|
`),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(f),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
147
147
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(H0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${c.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();Z.stdin.removeListener("data",Y);try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!1)}catch{}Z.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(f,z)=>{if(z==="%")return"%";if(Q>=$.length)return f;let B=$[Q++];switch(z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return f}}),Q<$.length)Y+=` ${$.slice(Q).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${Q}${W} ${c.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
148
148
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=Z.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,Z.stdout.write(w.lastRenderedLine),$)Z.stdout.write(`
|
|
149
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await bX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=S1(this.config.logDirectory,A);if(w.before)try{if((await L1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await uX(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 v9(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function m9(w){return w instanceof Yw}function
|
|
149
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await bX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=S1(this.config.logDirectory,A);if(w.before)try{if((await L1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await uX(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 v9(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function m9(w){return w instanceof Yw}function Fq(w){return w instanceof X8}function Tq(w){if(m9(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class j8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return EY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=cX.env[W]||(Q?cX.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=cX.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof J8)throw z;throw K$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw K$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(cX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
|
|
150
150
|
|
|
151
151
|
`;for(let A of w)Y+=`${A.key}
|
|
152
152
|
`,Y+=` Type: ${A.type}
|
|
@@ -158,36 +158,36 @@ ${A.join(`
|
|
|
158
158
|
`;Y+=`| Variable | Type | Description | Example |
|
|
159
159
|
`,Y+=`|----------|------|-------------|----------|
|
|
160
160
|
`;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
161
|
-
`;return Y}}function NN(w,$){let Y=p9("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function g9(w,$,Y={}){return d9(w,$,Y,new WeakMap)}function d9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return n9(w,$,X,A);if(!Gw($)||!Gw(w))return $;return MN(w,$,Y,A)}function n9(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 qN(w,$);case"smart":return HN(w,$,A);default:return $}return $}function qN(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>uW(X,A)))Y.push(A);return Y}function HN(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Gw($[0])&&Gw(w[0]))return RN(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 RN(w,$,Y){let A=[...$];for(let X of w){if(!Gw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Gw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function MN(w,$,Y,A){let X=$;if(Gw(X)&&A.has(X))return A.get(X);let J={...w};if(Gw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Gw(j)&&Gw(W))J[U]=d9(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=n9(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oW(w,$,Y="replace"){return g9(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function uW(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(!uW(w[Y],$[Y]))return!1;return!0}if(Gw(w)&&Gw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!uW(w[X],$[X]))return!1}return!0}return!1}function Gw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class Q8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=x1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!vX(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new BY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new BY(w,Error("Configuration must export a valid object"),"unknown");let F={config:oW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)x1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?K$.configLoad(w,Q):K$.configLoad(w,Error(String(Q)))}};if(U)return EY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(LW($,`${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 v9(async()=>{return vX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!vX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=LW(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=LW(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!vX(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 eW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await EY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!e7($))throw new GY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new GY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:o9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class wj{fileLoader=new Q8;envProcessor=new j8;validator=new eW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)yw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw yw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||Z$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(l0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw K$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?fY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)yw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)yw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?fY(w,Y,X):Y,j=[l0(y1(),".config",w),l0(y1(),".config"),y1()];for(let W of j){if(X)yw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)yw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?fY(w,A,J):A;try{let W=l0(Y,"package.json");if(!iW(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)yw.success(`Configuration loaded from package.json: ${z}`);return{config:oW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)yw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:fY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw K$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return x1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);x1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,l0(w,"config"),l0(w,".config"),$?l0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(l0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[l0(y1(),".config",w),l0(y1(),".config"),y1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function F9(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 yN(w){return w$.loadConfig({...w,__strictErrorHandling:!0})}async function l9(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await w$.loadConfig(w);else A=await w$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)yw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await w$.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function IN(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await w$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&F9(Y)))return(await w$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await w$.loadConfig({...w,cwd:w.cwd||Z$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&F9($)))return(await w$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function CN(w,$,Y="replace"){let A=new Q8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function fY(w,$,Y=!1){let A=new j8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=Z$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function VN(w){let $=l0(Z$.cwd(),w.configDir),Y=l0(Z$.cwd(),w.generatedDir),A=l0(Y,"config-types.ts");if(!iW(w9(A)))h7(w9(A),{recursive:!0,mode:511});let X=iW($)?_7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${$q}
|
|
161
|
+
`;return Y}}function qq(w,$){let Y=p9("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function g9(w,$,Y={}){return d9(w,$,Y,new WeakMap)}function d9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return n9(w,$,X,A);if(!Gw($)||!Gw(w))return $;return Mq(w,$,Y,A)}function n9(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 Nq(w,$);case"smart":return Hq(w,$,A);default:return $}return $}function Nq(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>uW(X,A)))Y.push(A);return Y}function Hq(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Gw($[0])&&Gw(w[0]))return Rq(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 Rq(w,$,Y){let A=[...$];for(let X of w){if(!Gw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Gw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function Mq(w,$,Y,A){let X=$;if(Gw(X)&&A.has(X))return A.get(X);let J={...w};if(Gw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Gw(j)&&Gw(W))J[U]=d9(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=n9(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oW(w,$,Y="replace"){return g9(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function uW(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(!uW(w[Y],$[Y]))return!1;return!0}if(Gw(w)&&Gw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!uW(w[X],$[X]))return!1}return!0}return!1}function Gw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class Q8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=x1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!vX(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new BY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new BY(w,Error("Configuration must export a valid object"),"unknown");let F={config:oW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)x1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?K$.configLoad(w,Q):K$.configLoad(w,Error(String(Q)))}};if(U)return EY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(LW($,`${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 v9(async()=>{return vX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!vX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=LW(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=LW(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!vX(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 eW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await EY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!e7($))throw new GY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new GY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:o9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class wj{fileLoader=new Q8;envProcessor=new j8;validator=new eW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)yw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw yw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||Z$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(l0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw K$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?fY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)yw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)yw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?fY(w,Y,X):Y,j=[l0(y1(),".config",w),l0(y1(),".config"),y1()];for(let W of j){if(X)yw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)yw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?fY(w,A,J):A;try{let W=l0(Y,"package.json");if(!iW(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)yw.success(`Configuration loaded from package.json: ${z}`);return{config:oW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)yw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:fY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw K$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return x1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);x1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,l0(w,"config"),l0(w,".config"),$?l0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(l0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[l0(y1(),".config",w),l0(y1(),".config"),y1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function F9(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 yq(w){return w$.loadConfig({...w,__strictErrorHandling:!0})}async function l9(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await w$.loadConfig(w);else A=await w$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)yw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await w$.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function Iq(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await w$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&F9(Y)))return(await w$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await w$.loadConfig({...w,cwd:w.cwd||Z$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&F9($)))return(await w$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function Cq(w,$,Y="replace"){let A=new Q8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function fY(w,$,Y=!1){let A=new j8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=Z$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function Vq(w){let $=l0(Z$.cwd(),w.configDir),Y=l0(Z$.cwd(),w.generatedDir),A=l0(Y,"config-types.ts");if(!iW(w9(A)))h7(w9(A),{recursive:!0,mode:511});let X=iW($)?_7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${$N}
|
|
162
162
|
export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
|
|
163
|
-
`;D7(A,J,{mode:438})}function
|
|
163
|
+
`;D7(A,J,{mode:438})}function Lq(w){let $=null,Y=null,A=()=>{if(!Y)Y=l9(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)yw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function Sq(w){let $=K9(Yq.cwd(),w?.configDir||"./config");function Y(){if(!wq($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=$q($).filter((W)=>X.has(SW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=SW(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=SW(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
|
|
164
164
|
${X.map((Q)=>{let f=K9($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${f}').default`}).join(`,
|
|
165
165
|
`)}
|
|
166
166
|
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
167
167
|
export type ConfigByName = ${j}
|
|
168
168
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
169
169
|
export type ConfigOf = Config
|
|
170
|
-
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function Jq(w,$={}){let Y=U8.cwd();while(Y.includes("storage"))Y=L9(Y,"..");let A=L9(Y,w||"");if($?.relative)return Xq(U8.cwd(),A);return A}function M0(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Fq(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ew<"u"){let w=ew.type;if(w==="renderer"||w==="worker")return!1;return!!(ew.versions&&(ew.versions.node||ew.versions.bun))}return!1}class Y2{async format(w){let $=await Fq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:D1.pid,hostname:$(),environment:D1.env.NODE_ENV||"development",platform:D1.platform,version:D1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D1.env.NODE_ENV||D1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class KY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...W8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Y2,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{...PW,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...PW};return{...PW,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:W8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await zq(this.config.logDirectory,_9.F_OK|_9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Bq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:aw.from(w);try{if(!gX(this.currentLogFile))await ZW(this.currentLogFile,"",{mode:420});if(X=h9(this.currentLogFile,"a",420),fq(X,W,{flag:"a"}),O9(X),X!==void 0)kW(X),X=void 0;if((await h1(this.currentLogFile)).size===0){if(await ZW(this.currentLogFile,W,{flag:"w",mode:420}),(await h1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{kW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return _1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return _1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return _1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return xW(16).toString("hex")}generateKey(){return xW(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=xW(16),A=Wq("aes-256-gcm",$,Y),X=aw.isBuffer(w)?w:aw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=aw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=x9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(aw.from(aw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await h1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await dX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await h1(Y).catch(()=>null))try{if(await D9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await nX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await ZW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await h1(Y).catch(()=>null))await D9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await dX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await nX(_1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=S9(w),A=Qq($),X=x9();await Kq(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()})),gX(this.currentLogFile))try{let w=h9(this.currentLogFile,"r+");O9(w),kW(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 dX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await nX(_1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=P.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${g.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(Gq($)||$.startsWith("./")||$.startsWith("../"))$=Eq($);else return null;return gX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Rq[w],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
170
|
+
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function JN(w,$={}){let Y=U8.cwd();while(Y.includes("storage"))Y=L9(Y,"..");let A=L9(Y,w||"");if($?.relative)return XN(U8.cwd(),A);return A}function M0(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function FN(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ew<"u"){let w=ew.type;if(w==="renderer"||w==="worker")return!1;return!!(ew.versions&&(ew.versions.node||ew.versions.bun))}return!1}class Y2{async format(w){let $=await FN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:D1.pid,hostname:$(),environment:D1.env.NODE_ENV||"development",platform:D1.platform,version:D1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D1.env.NODE_ENV||D1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class KY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...W8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Y2,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{...PW,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...PW};return{...PW,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:W8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await zN(this.config.logDirectory,_9.F_OK|_9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await BN(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:aw.from(w);try{if(!gX(this.currentLogFile))await ZW(this.currentLogFile,"",{mode:420});if(X=h9(this.currentLogFile,"a",420),fN(X,W,{flag:"a"}),O9(X),X!==void 0)kW(X),X=void 0;if((await h1(this.currentLogFile)).size===0){if(await ZW(this.currentLogFile,W,{flag:"w",mode:420}),(await h1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{kW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return _1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return _1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return _1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return xW(16).toString("hex")}generateKey(){return xW(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=xW(16),A=WN("aes-256-gcm",$,Y),X=aw.isBuffer(w)?w:aw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=aw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=x9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(aw.from(aw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await h1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await dX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await h1(Y).catch(()=>null))try{if(await D9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await nX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await ZW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await h1(Y).catch(()=>null))await D9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await dX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await nX(_1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=S9(w),A=QN($),X=x9();await KN(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()})),gX(this.currentLogFile))try{let w=h9(this.currentLogFile,"r+");O9(w),kW(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 dX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await nX(_1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=P.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${g.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(GN($)||$.startsWith("./")||$.startsWith("../"))$=EN($);else return null;return gX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":RN[w],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
171
171
|
`);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
|
|
172
172
|
`;if(j)f+=`${j}
|
|
173
173
|
`;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
|
|
174
174
|
`);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:Y,message:`${g.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
|
|
175
|
-
`,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":g.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new KY($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!gX(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=aw.isBuffer(w)?w:aw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=
|
|
175
|
+
`,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":g.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new KY($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!gX(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=aw.isBuffer(w)?w:aw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=jN("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=aw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
|
|
176
176
|
`),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(f),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
|
|
177
177
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(M0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${g.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();P.stdin.removeListener("data",Y);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(f,z)=>{if(z==="%")return"%";if(Q>=$.length)return f;let B=$[Q++];switch(z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return f}}),Q<$.length)Y+=` ${$.slice(Q).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${Q}${W} ${g.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
|
|
178
178
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?g.green("✓"):g.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=P.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,P.stdout.write(w.lastRenderedLine),$)P.stdout.write(`
|
|
179
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await 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=_1(this.config.logDirectory,A);if(w.before)try{if((await h1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var C7,V7=(w)=>w,S7=(w,$)=>{for(var Y in $)C7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:L7.bind($,Y)})},O7=(w,$)=>()=>(w&&($=w(w=0)),$),P9,p9,x1,EY,r9,ON,hN,T9,pX,cW,k0,w0,_N,N9,DN,q9,xN,kN,OW,ZN,H9,R9,hW,PN,iN,bN,uN,rX,t9,cN,Z0,vN,mN,M9,tX,vW,R0,c,gN,y9,dN,I9,nN,lN,_W,pN,C9,V9,rN,DW,tN,aN,sN,oN,eN,aX,a9,wq,$q="0.15.6",Yw,X8,BY,mW,gW,J8,dW,nW,GY,lW,pW,K$,s9,o9,yw,w$,e9,w2,Yq,Uq,$2,W8,K3,C0,g,V3,Tq,L3,Nq,S3,O3,k9,h3,qq,Hq,_3,Z9,D3,x3,k3,Z3,P3,PW,Rq,i3;var A2=s(()=>{C7=Object.defineProperty;P9={};S7(P9,{withErrorRecovery:()=>v9,tryLoadConfig:()=>CN,loadConfigWithResult:()=>yN,loadConfig:()=>l9,isRetryableError:()=>TN,isConfigNotFoundError:()=>FN,isBunfigError:()=>m9,globalPerformanceMonitor:()=>EY,globalCache:()=>x1,getEnvOrDefault:()=>NN,generateConfigTypes:()=>VN,defaultGeneratedDir:()=>w2,defaultConfigDir:()=>e9,deepMergeWithArrayStrategy:()=>oW,deepMerge:()=>g9,createLibraryConfig:()=>LN,config:()=>IN,bunfigPlugin:()=>SN,applyEnvVarsToConfig:()=>fY,TypeGenerationError:()=>nW,SchemaValidationError:()=>GY,PluginError:()=>pW,PerformanceMonitor:()=>tW,FileSystemError:()=>dW,ErrorFactory:()=>K$,EnvVarError:()=>J8,EnvProcessor:()=>j8,ConfigValidator:()=>eW,ConfigValidationError:()=>mW,ConfigNotFoundError:()=>X8,ConfigMergeError:()=>gW,ConfigLoader:()=>wj,ConfigLoadError:()=>BY,ConfigFileLoader:()=>Q8,ConfigCache:()=>rW,CacheUtils:()=>r9,BunfigError:()=>Yw,BrowserConfigError:()=>lW,ArrayMergeStrategies:()=>s9});Yq=O7(async()=>{p9=import.meta.require,x1=new rW,EY=new tW,r9={createKey:AN,isEquivalent:XN,estimateMemoryUsage:JN},ON=eX(bW.cwd(),"config"),hN=eX(bW.cwd(),"src/generated"),T9=oX.env.CLARITY_LOG_DIR||Z7(jN(),"logs"),pX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:T9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},cW=await QN(),k0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},w0=k0,_N=k0.red,N9=k0.green,DN=k0.yellow,q9=k0.blue,xN=k0.magenta,kN=k0.cyan,OW=k0.white,ZN=k0.gray,H9=k0.bgRed,R9=k0.bgYellow,hW=k0.bold,PN=k0.dim,iN=k0.italic,bN=k0.underline,uN=k0.reset,rX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t9={debug:"\uD83D\uDD0D",info:q9("ℹ"),success:N9("✓"),warning:R9(OW(hW(" WARN "))),error:H9(OW(hW(" ERROR ")))},cN=new $8("stacks"),Z0=new $8("bunfig",{showTags:!0}),vN=n0(zY.cwd(),"config"),mN=n0(zY.cwd(),"src/generated"),M9=sX.env.CLARITY_LOG_DIR||x7(GN(),"logs"),tX={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},vW=await EN(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=R0,gN=R0.red,y9=R0.green,dN=R0.yellow,I9=R0.blue,nN=R0.magenta,lN=R0.cyan,_W=R0.white,pN=R0.gray,C9=R0.bgRed,V9=R0.bgYellow,rN=R0.bgGray,DW=R0.bold,tN=R0.dim,aN=R0.italic,sN=R0.underline,oN=R0.strikethrough,eN=R0.reset,aX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a9={debug:"\uD83D\uDD0D",info:I9("ℹ"),success:y9("✓"),warning:V9(_W(DW(" WARN "))),error:C9(_W(DW(" ERROR ")))},wq=new A8("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}${$}`}},X8=class extends Yw{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},BY=class extends Yw{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},mW=class extends Yw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},gW=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}},J8=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})}},dW=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}},nW=class extends Yw{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},GY=class extends Yw{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},lW=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})}},pW=class extends Yw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},K$={configNotFound(w,$,Y){return new X8(w,$,Y)},configLoad(w,$,Y){return new BY(w,$,Y)},configValidation(w,$,Y){return new mW(w,$,Y)},configMerge(w,$,Y,A){return new gW(w,$,Y,A)},envVar(w,$,Y,A){return new J8(w,$,Y,A)},fileSystem(w,$,Y){return new dW(w,$,Y)},typeGeneration(w,$,Y){return new nW(w,$,Y)},schemaValidation(w,$,Y){return new GY(w,$,Y)},browserConfig(w,$,Y,A){return new lW(w,$,Y,A)},plugin(w,$,Y){return new pW(w,$,Y)}},s9={replace:"replace",concat:"concat",smart:"smart"},o9=/^https?:\/\//,yw=new A8("bunfig",{showTags:!0}),w$=new wj,e9=l0(Z$.cwd(),"config"),w2=l0(Z$.cwd(),"src/generated")});Uq=U8.env.CLARITY_LOG_DIR||Aq(Jq(),"logs"),$2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Uq,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W8={...$2},K3=(async()=>{try{let{loadConfig:w}=await Yq().then(()=>P9),$=await w({name:"clarity",alias:"logging",defaultConfig:$2,cwd:U8.cwd()});if($)Object.assign(W8,$)}catch{}return W8})();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,V3=C0.red,Tq=C0.green,L3=C0.yellow,Nq=C0.blue,S3=C0.magenta,O3=C0.cyan,k9=C0.white,h3=C0.gray,qq=C0.bgRed,Hq=C0.bgYellow,_3=C0.bgGray,Z9=C0.bold,D3=C0.dim,x3=C0.italic,k3=C0.underline,Z3=C0.strikethrough,P3=C0.reset,PW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Rq={debug:"\uD83D\uDD0D",info:Nq("ℹ"),success:Tq("✓"),warning:Hq(k9(Z9(" WARN "))),error:qq(k9(Z9(" ERROR ")))};i3=new KY("stacks")});var k1={};ej(k1,{shouldReusePort:()=>TY,safeStringify:()=>$$,safeDeleteFile:()=>Aj,resolvePathRewrite:()=>Yj,redactSensitive:()=>z8,isValidRootCA:()=>$j,isSingleProxyOptions:()=>NY,isSingleProxyConfig:()=>Sq,isProcessElevated:()=>FY,isMultiProxyOptions:()=>P$,isMultiProxyConfig:()=>G8,getSudoPassword:()=>F$,getPrimaryDomain:()=>B8,extractHostname:()=>Lq,execSudoSync:()=>T$,debugLog:()=>E,authorizeSystemAccess:()=>yq});import{execSync as f8}from"node:child_process";import*as J2 from"node:fs/promises";function F$(){return process.env.SUDO_PASSWORD}function FY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function yq(w={}){if(process.platform==="win32")return!0;if(FY()||!!F$())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 T$(w){if(FY())return f8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=F$(),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 E(w,$,Y){if(Y)Mq.debug(`[rpx:${w}] ${$}`)}function TY(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function Vq(w){let $=w.toLowerCase();return Iq.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function z8(w){if(Array.isArray(w))return w.map((Y)=>z8(Y));if(typeof w==="string")return Cq.test(w)?X2:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(Vq(Y)){$[Y]=X2;continue}$[Y]=z8(A)}return $}function $$(w,$){return JSON.stringify(z8(w),null,$)}function Lq(w){if(P$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(NY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function $j(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function B8(w){if(!w)return"stacks.localhost";if(P$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(NY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function G8(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function P$(w){return"proxies"in w&&Array.isArray(w.proxies)}function NY(w){return"to"in w&&typeof w.to==="string"}function Sq(w){return!!(w&&("to"in w)&&!("proxies"in w))}function Yj(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 Aj(w,$){try{await J2.unlink(w),E("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var Mq,X2="[redacted]",Iq,Cq;var z0=s(()=>{A2();Mq=new KY("rpx",{showTags:!1});Iq=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Cq=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as E8}from"node:child_process";import{homedir as Oq}from"node:os";import{join as hq}from"node:path";function K8(){return hq(Oq(),"Library/Keychains/login.keychain-db")}function Jj(){return[q$,K8()]}function U2(w,$=Xj){let Y=E8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
|
|
179
|
+
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await 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=_1(this.config.logDirectory,A);if(w.before)try{if((await h1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var C7,V7=(w)=>w,S7=(w,$)=>{for(var Y in $)C7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:L7.bind($,Y)})},O7=(w,$)=>()=>(w&&($=w(w=0)),$),P9,p9,x1,EY,r9,Oq,hq,T9,pX,cW,k0,w0,_q,q9,Dq,N9,xq,kq,OW,Zq,H9,R9,hW,Pq,iq,bq,uq,rX,t9,cq,Z0,vq,mq,M9,tX,vW,R0,c,gq,y9,dq,I9,nq,lq,_W,pq,C9,V9,rq,DW,tq,aq,sq,oq,eq,aX,a9,wN,$N="0.15.6",Yw,X8,BY,mW,gW,J8,dW,nW,GY,lW,pW,K$,s9,o9,yw,w$,e9,w2,YN,UN,$2,W8,K3,C0,g,V3,TN,L3,qN,S3,O3,k9,h3,NN,HN,_3,Z9,D3,x3,k3,Z3,P3,PW,RN,i3;var A2=s(()=>{C7=Object.defineProperty;P9={};S7(P9,{withErrorRecovery:()=>v9,tryLoadConfig:()=>Cq,loadConfigWithResult:()=>yq,loadConfig:()=>l9,isRetryableError:()=>Tq,isConfigNotFoundError:()=>Fq,isBunfigError:()=>m9,globalPerformanceMonitor:()=>EY,globalCache:()=>x1,getEnvOrDefault:()=>qq,generateConfigTypes:()=>Vq,defaultGeneratedDir:()=>w2,defaultConfigDir:()=>e9,deepMergeWithArrayStrategy:()=>oW,deepMerge:()=>g9,createLibraryConfig:()=>Lq,config:()=>Iq,bunfigPlugin:()=>Sq,applyEnvVarsToConfig:()=>fY,TypeGenerationError:()=>nW,SchemaValidationError:()=>GY,PluginError:()=>pW,PerformanceMonitor:()=>tW,FileSystemError:()=>dW,ErrorFactory:()=>K$,EnvVarError:()=>J8,EnvProcessor:()=>j8,ConfigValidator:()=>eW,ConfigValidationError:()=>mW,ConfigNotFoundError:()=>X8,ConfigMergeError:()=>gW,ConfigLoader:()=>wj,ConfigLoadError:()=>BY,ConfigFileLoader:()=>Q8,ConfigCache:()=>rW,CacheUtils:()=>r9,BunfigError:()=>Yw,BrowserConfigError:()=>lW,ArrayMergeStrategies:()=>s9});YN=O7(async()=>{p9=import.meta.require,x1=new rW,EY=new tW,r9={createKey:Aq,isEquivalent:Xq,estimateMemoryUsage:Jq},Oq=eX(bW.cwd(),"config"),hq=eX(bW.cwd(),"src/generated"),T9=oX.env.CLARITY_LOG_DIR||Z7(jq(),"logs"),pX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:T9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},cW=await Qq(),k0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},w0=k0,_q=k0.red,q9=k0.green,Dq=k0.yellow,N9=k0.blue,xq=k0.magenta,kq=k0.cyan,OW=k0.white,Zq=k0.gray,H9=k0.bgRed,R9=k0.bgYellow,hW=k0.bold,Pq=k0.dim,iq=k0.italic,bq=k0.underline,uq=k0.reset,rX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},t9={debug:"\uD83D\uDD0D",info:N9("ℹ"),success:q9("✓"),warning:R9(OW(hW(" WARN "))),error:H9(OW(hW(" ERROR ")))},cq=new $8("stacks"),Z0=new $8("bunfig",{showTags:!0}),vq=n0(zY.cwd(),"config"),mq=n0(zY.cwd(),"src/generated"),M9=sX.env.CLARITY_LOG_DIR||x7(Gq(),"logs"),tX={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},vW=await Eq(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=R0,gq=R0.red,y9=R0.green,dq=R0.yellow,I9=R0.blue,nq=R0.magenta,lq=R0.cyan,_W=R0.white,pq=R0.gray,C9=R0.bgRed,V9=R0.bgYellow,rq=R0.bgGray,DW=R0.bold,tq=R0.dim,aq=R0.italic,sq=R0.underline,oq=R0.strikethrough,eq=R0.reset,aX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a9={debug:"\uD83D\uDD0D",info:I9("ℹ"),success:y9("✓"),warning:V9(_W(DW(" WARN "))),error:C9(_W(DW(" ERROR ")))},wN=new A8("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}${$}`}},X8=class extends Yw{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},BY=class extends Yw{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},mW=class extends Yw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},gW=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}},J8=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})}},dW=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}},nW=class extends Yw{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},GY=class extends Yw{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},lW=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})}},pW=class extends Yw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},K$={configNotFound(w,$,Y){return new X8(w,$,Y)},configLoad(w,$,Y){return new BY(w,$,Y)},configValidation(w,$,Y){return new mW(w,$,Y)},configMerge(w,$,Y,A){return new gW(w,$,Y,A)},envVar(w,$,Y,A){return new J8(w,$,Y,A)},fileSystem(w,$,Y){return new dW(w,$,Y)},typeGeneration(w,$,Y){return new nW(w,$,Y)},schemaValidation(w,$,Y){return new GY(w,$,Y)},browserConfig(w,$,Y,A){return new lW(w,$,Y,A)},plugin(w,$,Y){return new pW(w,$,Y)}},s9={replace:"replace",concat:"concat",smart:"smart"},o9=/^https?:\/\//,yw=new A8("bunfig",{showTags:!0}),w$=new wj,e9=l0(Z$.cwd(),"config"),w2=l0(Z$.cwd(),"src/generated")});UN=U8.env.CLARITY_LOG_DIR||AN(JN(),"logs"),$2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:UN,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W8={...$2},K3=(async()=>{try{let{loadConfig:w}=await YN().then(()=>P9),$=await w({name:"clarity",alias:"logging",defaultConfig:$2,cwd:U8.cwd()});if($)Object.assign(W8,$)}catch{}return W8})();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,V3=C0.red,TN=C0.green,L3=C0.yellow,qN=C0.blue,S3=C0.magenta,O3=C0.cyan,k9=C0.white,h3=C0.gray,NN=C0.bgRed,HN=C0.bgYellow,_3=C0.bgGray,Z9=C0.bold,D3=C0.dim,x3=C0.italic,k3=C0.underline,Z3=C0.strikethrough,P3=C0.reset,PW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RN={debug:"\uD83D\uDD0D",info:qN("ℹ"),success:TN("✓"),warning:HN(k9(Z9(" WARN "))),error:NN(k9(Z9(" ERROR ")))};i3=new KY("stacks")});var k1={};ej(k1,{shouldReusePort:()=>TY,safeStringify:()=>$$,safeDeleteFile:()=>Aj,resolvePathRewrite:()=>Yj,redactSensitive:()=>z8,isValidRootCA:()=>$j,isSingleProxyOptions:()=>qY,isSingleProxyConfig:()=>SN,isProcessElevated:()=>FY,isMultiProxyOptions:()=>P$,isMultiProxyConfig:()=>G8,getSudoPassword:()=>F$,getPrimaryDomain:()=>B8,extractHostname:()=>LN,execSudoSync:()=>T$,debugLog:()=>E,authorizeSystemAccess:()=>yN});import{execSync as f8}from"node:child_process";import*as J2 from"node:fs/promises";function F$(){return process.env.SUDO_PASSWORD}function FY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function yN(w={}){if(process.platform==="win32")return!0;if(FY()||!!F$())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 T$(w){if(FY())return f8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=F$(),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 E(w,$,Y){if(Y)MN.debug(`[rpx:${w}] ${$}`)}function TY(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function VN(w){let $=w.toLowerCase();return IN.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function z8(w){if(Array.isArray(w))return w.map((Y)=>z8(Y));if(typeof w==="string")return CN.test(w)?X2:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(VN(Y)){$[Y]=X2;continue}$[Y]=z8(A)}return $}function $$(w,$){return JSON.stringify(z8(w),null,$)}function LN(w){if(P$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(qY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function $j(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function B8(w){if(!w)return"stacks.localhost";if(P$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(qY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function G8(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function P$(w){return"proxies"in w&&Array.isArray(w.proxies)}function qY(w){return"to"in w&&typeof w.to==="string"}function SN(w){return!!(w&&("to"in w)&&!("proxies"in w))}function Yj(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 Aj(w,$){try{await J2.unlink(w),E("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var MN,X2="[redacted]",IN,CN;var z0=s(()=>{A2();MN=new KY("rpx",{showTags:!1});IN=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),CN=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as E8}from"node:child_process";import{homedir as ON}from"node:os";import{join as hN}from"node:path";function K8(){return hN(ON(),"Library/Keychains/login.keychain-db")}function Jj(){return[N$,K8()]}function U2(w,$=Xj){let Y=E8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
|
|
180
180
|
`)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function Uj(w){if(process.platform!=="darwin")return;let $=k$(w.caPath);if(!$)return;let Y=w.commonName??Xj,A=w.keychains??Jj();for(let X of A)for(let J of U2(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))T$(`security delete-certificate -Z ${J} "${X}"`);else E8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function Wj(w,$,Y){if(process.platform!=="darwin")return F8(w,Y);try{let X=E8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function F8(w,$){let Y=k$(w);if(!Y)return!1;for(let A of Jj())try{let X=E8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
|
|
181
|
-
`))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var
|
|
181
|
+
`))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var q$="-d -r trustRoot -p ssl -p basic",N$="/Library/Keychains/System.keychain",Xj="rpx.localhost";var jj=s(()=>{kX();z0()});import{execSync as Qj}from"node:child_process";import B0 from"node:fs/promises";import*as fj from"node:os";import{homedir as Z1}from"node:os";import*as Q2 from"node:path";import{join as G0}from"node:path";import*as H$ from"node:process";function f2(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function z2(w,$,Y){let A=G0(Z1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:zj,keyPath:G0(A,"rpx.localhost.key"),caCertPath:G0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function B2(w){return{caCertPath:G0(w,DN),caKeyPath:G0(w,xN)}}async function kN(w,$){try{let[Y,A]=await Promise.all([B0.readFile(w.caCertPath,"utf8"),B0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return E("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function W2(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 G2(w){let Y=B8(w).replace(/\*/g,"wildcard"),A=G0(Z1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||G0(X,`${Y}.ca.crt`),certPath:w.https.certPath||G0(X,`${Y}.crt`),keyPath:w.https.keyPath||G0(X,`${Y}.key`)};return{caCertPath:G0(X,`${Y}.ca.crt`),certPath:G0(X,`${Y}.crt`),keyPath:G0(X,`${Y}.key`)}}function j2(w){let $=new Set;if(P$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";W2(A).forEach((X)=>$.add(X))});else if(qY(w)){let Y=w.to||"rpx.localhost";W2(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function NY(w){if(R$&&!w.forceRegenerate){E("ssl","Using cached SSL configuration",w.verbose);return}Bj();let $=P$(w)?w.proxies.map((f)=>f.to):[w.to];E("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=HY(w,w.verbose),A=Y.basePath||G0(Z1(),".stacks","ssl");await B0.mkdir(A,{recursive:!0});let X=B2(A),J=await kN(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await BW(Y);try{await Promise.all([B0.writeFile(X.caCertPath,J.certificate),B0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,E("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(f){throw E("ssl",`Error saving Root CA files: ${f}`,w.verbose),Error(`Failed to save Root CA files: ${f}`)}}else E("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let j=await GW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([B0.writeFile(Y.certPath,j.certificate),B0.writeFile(Y.keyPath,j.privateKey),B0.writeFile(Y.caCertPath,J.certificate)]),E("ssl","Certificate files saved successfully",w.verbose)}catch(f){throw E("ssl",`Error saving certificate files: ${f}`,w.verbose),Error(`Failed to save certificate files: ${f}`)}if(U?!1:await K2(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let Q=!1;if(H$.platform==="darwin")try{Uj({caPath:X.caCertPath,verbose:w.verbose});let f=K8();try{Qj(`security add-trusted-cert ${q$} -k "${f}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(T$(`security add-trusted-cert ${q$} -k ${N$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");Q=!0;let z=G0(A,"trust-rpx-cert.sh"),B=`#!/bin/bash
|
|
182
182
|
echo "Trusting RPX Root CA"
|
|
183
183
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
184
184
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
185
185
|
if [ -n "$SUDO_PASSWORD" ]
|
|
186
186
|
then
|
|
187
187
|
printf '%s
|
|
188
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
188
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${q$} -k ${N$} "${X.caCertPath}"
|
|
189
189
|
else
|
|
190
|
-
sudo security add-trusted-cert ${
|
|
190
|
+
sudo security add-trusted-cert ${q$} -k ${N$} "${X.caCertPath}"
|
|
191
191
|
fi
|
|
192
192
|
echo "Root CA trusted! Please restart your browser."
|
|
193
193
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
@@ -198,9 +198,9 @@ echo "Trusting RPX Root CA"
|
|
|
198
198
|
if [ -n "$SUDO_PASSWORD" ]
|
|
199
199
|
then
|
|
200
200
|
printf '%s
|
|
201
|
-
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${
|
|
201
|
+
' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${q$} -k ${N$} "${X.caCertPath}"
|
|
202
202
|
else
|
|
203
|
-
sudo security add-trusted-cert ${
|
|
203
|
+
sudo security add-trusted-cert ${q$} -k ${N$} "${X.caCertPath}"
|
|
204
204
|
fi
|
|
205
205
|
echo "Root CA trusted! Please restart your browser."
|
|
206
206
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
@@ -216,10 +216,10 @@ $store.Open("ReadWrite")
|
|
|
216
216
|
$store.Add($cert)
|
|
217
217
|
$store.Close()
|
|
218
218
|
Write-Host "Root CA trusted successfully!"
|
|
219
|
-
`,z=G0(fj.tmpdir(),"rpx-trust.ps1");if(await B0.writeFile(z,f),Qj(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");Q=!0}catch(f){if(w.verbose)H.warn(`Could not trust certificate: ${f}`)}else try{await FW(j,J.certificate,Y),Q=!0}catch(f){if(w.verbose)H.warn(`Could not add certificate to trust store: ${f}`)}if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!Q&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function Bj(){R$=null}async function M$(w){if(!w)return null;if(R$)return R$;let $=HY(w);try{let[Y,A,X]=await Promise.all([B0.access($.keyPath).then(()=>!0).catch(()=>!1),B0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?B0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,j=J?U!==!1:!0;E("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${j}`,w.verbose);let W=$.basePath||G0(Z1(),".stacks","ssl"),Q=B2(W);if(!(j?await K2(Q.caCertPath,w):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,B,G]=await Promise.all([B0.readFile($.keyPath,"utf8"),B0.readFile($.certPath,"utf8"),X&&$.caCertPath?B0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(G&&!G.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(P$(w))try{let{X509Certificate:T}=await import("node:crypto"),F=new T(B).subjectAltName||"",R=w.proxies.map((V)=>V.to).filter((V)=>!F.includes(`DNS:${V}`));if(R.length>0)return E("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,w.verbose)}return E("ssl","Successfully loaded existing certificates",w.verbose),R$={key:z,cert:B,ca:G},R$}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function HY(w,$){let Y=B8(w);E("ssl",`Primary domain: ${Y}`,$);let A=G2(w),X=G0(Z1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(j2(w)).map((j)=>({type:2,value:j}))};if($j(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(j2(w)).map((J)=>({type:2,value:J}))}}async function E2(w,$){let Y=G2({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>Aj(X,$)))}async function K2(w,$){try{if(E("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),H$.platform==="darwin"){if($?.serverName)return Wj(w,$.serverName,{verbose:$?.verbose});return F8(w,{verbose:$?.verbose})}else if(H$.platform==="win32")try{let Y=TW(w)||"";if(!Y)return E("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Qj(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",$?.verbose),!0;return E("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(H$.platform==="linux")try{let Y=k$(w);if(!Y)return E("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await B0.readdir(X)}catch{continue}for(let U of J){let j=k$(Q2.join(X,U));if(j&&j===Y)return E("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return E("ssl",`Platform ${H$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var R$=null,zj,
|
|
220
|
-
`)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function CY(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=
|
|
219
|
+
`,z=G0(fj.tmpdir(),"rpx-trust.ps1");if(await B0.writeFile(z,f),Qj(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");Q=!0}catch(f){if(w.verbose)H.warn(`Could not trust certificate: ${f}`)}else try{await FW(j,J.certificate,Y),Q=!0}catch(f){if(w.verbose)H.warn(`Could not add certificate to trust store: ${f}`)}if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!Q&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function Bj(){R$=null}async function M$(w){if(!w)return null;if(R$)return R$;let $=HY(w);try{let[Y,A,X]=await Promise.all([B0.access($.keyPath).then(()=>!0).catch(()=>!1),B0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?B0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,j=J?U!==!1:!0;E("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${j}`,w.verbose);let W=$.basePath||G0(Z1(),".stacks","ssl"),Q=B2(W);if(!(j?await K2(Q.caCertPath,w):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,B,G]=await Promise.all([B0.readFile($.keyPath,"utf8"),B0.readFile($.certPath,"utf8"),X&&$.caCertPath?B0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(G&&!G.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(P$(w))try{let{X509Certificate:T}=await import("node:crypto"),F=new T(B).subjectAltName||"",R=w.proxies.map((V)=>V.to).filter((V)=>!F.includes(`DNS:${V}`));if(R.length>0)return E("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,w.verbose)}return E("ssl","Successfully loaded existing certificates",w.verbose),R$={key:z,cert:B,ca:G},R$}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function HY(w,$){let Y=B8(w);E("ssl",`Primary domain: ${Y}`,$);let A=G2(w),X=G0(Z1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(j2(w)).map((j)=>({type:2,value:j}))};if($j(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(j2(w)).map((J)=>({type:2,value:J}))}}async function E2(w,$){let Y=G2({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>Aj(X,$)))}async function K2(w,$){try{if(E("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),H$.platform==="darwin"){if($?.serverName)return Wj(w,$.serverName,{verbose:$?.verbose});return F8(w,{verbose:$?.verbose})}else if(H$.platform==="win32")try{let Y=TW(w)||"";if(!Y)return E("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Qj(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",$?.verbose),!0;return E("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(H$.platform==="linux")try{let Y=k$(w);if(!Y)return E("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await B0.readdir(X)}catch{continue}for(let U of J){let j=k$(Q2.join(X,U));if(j&&j===Y)return E("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return E("ssl",`Platform ${H$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var R$=null,zj,DN="rpx-root-ca.crt",xN="rpx-root-ca.key";var Gj=s(()=>{xX();_$();bA();jj();z0();jj();kX();kX();zj=G0(Z1(),".stacks","ssl","rpx.localhost.crt")});function ZN(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 PN(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function F2(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function i$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function RY(w,$){return{upstreams:PN(w),strategy:$?.strategy??"round-robin",healthCheck:ZN($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function iN(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function bN(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function uN(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 cN(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function T2(w){let $=iN(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return uN(w,$);case"least-connections":return cN($);case"round-robin":default:return bN(w,$)}}function T8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function MY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function vN(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 mN(w,$){let{hostname:Y,port:A}=vN($.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(()=>{}),T8(w,$)}catch{MY(w,$)}finally{clearTimeout(J)}}function yY(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)mN(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function P1(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as N2,timingSafeEqual as q2}from"node:crypto";import{readFileSync as gN}from"node:fs";function IY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return q2(Y,Y),!1;return q2(Y,A)}function nN(w,$){let Y=(B)=>N2("md5").update(B).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let B=A.length;B>0;B-=16)U.push(J.subarray(0,Math.min(B,16)));for(let B=A.length;B>0;B>>=1)U.push(B&1?Buffer.from([0]):A.subarray(0,1));let j=Y(Buffer.concat(U));for(let B=0;B<1000;B++){let G=[];if(G.push(B&1?A:j.subarray(0,16)),B%3)G.push(X);if(B%7)G.push(A);G.push(B&1?j.subarray(0,16):A),j=Y(Buffer.concat(G))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Q=(B,G)=>{let T="",K=B;for(let F=0;F<G;F++)T+=W[K&63],K>>=6;return T},f=j,z="";return z+=Q(f[0]<<16|f[6]<<8|f[12],4),z+=Q(f[1]<<16|f[7]<<8|f[13],4),z+=Q(f[2]<<16|f[8]<<8|f[14],4),z+=Q(f[3]<<16|f[9]<<8|f[15],4),z+=Q(f[4]<<16|f[10]<<8|f[5],4),z+=Q(f[11],2),`$apr1$${$}$${z}`}function lN(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return IY(nN(w,A),$)}if($.startsWith("{SHA}")){let Y=N2("sha1").update(w,"utf8").digest("base64");return IY(`{SHA}${Y}`,$)}return IY(w,$)}function pN(w){let $=new Map;for(let Y of w.split(`
|
|
220
|
+
`)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function CY(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=pN(gN(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let j=!1;for(let W of Y)if(IY(J,W.username)&&IY(U,W.password))j=!0;if(A){let W=A.get(J);if(W&&lN(U,W))j=!0}return j}}}function H2(w,$,Y){if($.startsWith(dN))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let W="";try{W=Buffer.from(U,"base64").toString("utf8")}catch{W=""}let Q=W.indexOf(":");if(Q>=0&&Y.verify(W.slice(0,Q),W.slice(Q+1)))return}let j=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${j}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var dN="/.well-known/acme-challenge/";var q8=()=>{};function aN(w){return tN.has(w.toUpperCase())}function sN(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function oN(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function eN(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function wH(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function $H(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class C2{socket=null;buf=new Uint8Array(YH);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw N8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>AH)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=XH)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 V2{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=sN();maxWaiters;checkoutIdleMs=eN();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=oN(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new C2;return rN({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=wH();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw b$;let w=await this.waitForSlot();if(w===b$)throw b$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(b$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(Ej,this.checkoutIdleMs):Ej;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-Ej;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&&H8.get(this.key)===this)H8.delete(this.key)}}}function QH(w,$){let Y=H8.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 V2(X,J,$??$H(),w),H8.set(w,Y)}return Y}function R2(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 fH(w,$,Y){let A=I2.decode(w.subarray($,Y)),X=A.indexOf(`\r
|
|
221
221
|
`),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),j=Number.parseInt(J.slice(U+1,U+5),10),W=J.startsWith("HTTP/1.0"),Q=[],f=-1,z=!1,B=W,G=!1,T=!1,K=X===-1?A.length:X+2;while(K<A.length){let F=A.indexOf(`\r
|
|
222
|
-
`,K);if(F===-1)F=A.length;let
|
|
222
|
+
`,K);if(F===-1)F=A.length;let q=A.slice(K,F);if(K=F+2,q==="")continue;let R=q.indexOf(":");if(R===-1)continue;let V=q.slice(0,R),L=q.slice(R+1).trim(),N=V.charCodeAt(0)|32;if(N===99||N===116||N===107){let C=V.toLowerCase();if(C==="content-length"){let M=/^\d+$/.test(L)?Number(L):Number.NaN;if(!Number.isSafeInteger(M)||f>=0&&f!==M)T=!0;else f=M;continue}if(C==="transfer-encoding"){if(L.toLowerCase().includes("chunked"))z=!0;continue}if(C==="connection"){let M=L.toLowerCase();if(M.includes("close"))B=!0;if(M.includes("keep-alive"))G=!0;continue}if(C==="keep-alive")continue}Q.push([V,L])}if(W&&G)B=!1;if(z&&f>=0)f=-1;return{status:j,headerEnd:Y,headers:Q,contentLength:f,chunked:z,closeConn:B,malformed:T}}function zH(w,$){return $||w===204||w===304}async function L2(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:j}=w,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw VY;let Q=null;if(j){let G=X.get("content-length"),T=G?Number.parseInt(G,10):Number.NaN;if(Number.isNaN(T)||T>M2)throw VY;if(Q=await qH(j),Q===null)throw VY}let f=TH(Y,A,X,$,J,U,Q),z=f;if(Q&&Q.length)z=new Uint8Array(f.length+Q.length),z.set(f),z.set(Q,f.length);let B=QH($,w.maxPerHost);for(let G=0;;G++){if(G>0)await new Promise((K)=>{setTimeout(K,G)});let T;try{T=B.acquireIdleSync()??await B.acquireOrDial()}catch(K){if(K!==b$&&G<4)continue;throw K}try{let K=T.socket.write(z);if(K<z.length)await T.writeAll(z.subarray(K));return await GH(B,T,W,w.signal)}catch(K){let F=K===N8&&G<4&&(T.fresh||aN(Y));if(B.destroy(T),F)continue;if(K===N8)throw Error("upstream closed connection");throw K}}}async function BH(w){let $=R2(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw Kj;if(w.len===w.pos)throw N8;throw Error("upstream closed mid-header")}if(w.len-w.pos>y2)throw Error("upstream header block too large");await w.waitForData(w.len),$=R2(w.buf,w.len,w.pos)}return $}async function GH(w,$,Y,A){let X;for(;;){let U=await BH($);if(X=fH($.buf,$.pos,U),$.pos=U+4,X.status>=100&&X.status<200)continue;break}if(X.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let J=X.headers;if(zH(X.status,Y))return S2(w,$,X.closeConn),new Response(null,{status:X.status,headers:J});if(X.chunked)return new Response(FH(w,$,X.closeConn,A),{status:X.status,headers:J});if(X.contentLength>=0){if($.len-$.pos>=X.contentLength){let j=$.pos+X.contentLength,W=$.len>j,Q=null;if(X.contentLength>=JH)Q=$.buf.subarray($.pos,j),$.buf=new Uint8Array(UH);else if(X.contentLength>0)Q=$.buf.slice($.pos,j);if($.pos=0,$.len=0,X.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:X.status,headers:J})}return new Response(EH(w,$,X.contentLength,X.closeConn),{status:X.status,headers:J})}return new Response(KH($),{status:X.status,headers:J})}function S2(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function EH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(j)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);j.close()};return new ReadableStream({start(j){if(J)j.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(j)},async pull(j){for(;;){let W=$.bodyQueue;if(W&&W.length>0){let Q=W.shift();if($.queuedBytes-=Q.length,$.resumeIfDrained(),j.enqueue(Q),$.bodyRemaining===0&&W.length===0)U(j);return}if($.bodyRemaining===0){if($.bodyQueue)U(j);return}if($.closed){$.bodyQueue=null,w.destroy($),j.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function KH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function FH(w,$,Y,A){$.streamingBody=!0;let X=0,J=!1,U=!1,j,W=()=>A?.removeEventListener("abort",Q),Q=()=>{if(U)return;U=!0,w.destroy($);try{j?.close()}catch{}};async function f(z=!1){for(;;){for(let B=$.pos;B+1<$.len;B++)if($.buf[B]===13&&$.buf[B+1]===10){let G=I2.decode($.buf.subarray($.pos,B));return $.pos=B+2,G}if($.closed){if(z&&$.pos===$.len)return null;throw Error("upstream closed mid-chunk-header")}if($.len-$.pos>y2)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({start(z){if(j=z,A?.aborted)Q();else A?.addEventListener("abort",Q,{once:!0})},async pull(z){try{for(;;){if(X>0){if($.len===$.pos){if($.closed){w.destroy($),z.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let K=Math.min(X,$.len-$.pos);if(z.enqueue($.buf.slice($.pos,$.pos+K)),$.pos+=K,X-=K,$.resumeIfDrained(),X===0)J=!0;return}if(J)await f(),J=!1;let B=await f(!0);if(B===null){w.destroy($),W(),z.close();return}let G=B.indexOf(";"),T=Number.parseInt(G===-1?B:B.slice(0,G),16);if(!Number.isInteger(T)||T<0){w.destroy($),z.error(Error("upstream sent malformed chunk size"));return}if(T===0){for(;;)if(await f()==="")break;S2(w,$,Y),W(),z.close();return}X=T}}catch(B){if(w.destroy($),W(),!U)z.error(B)}},cancel(){U=!0,W(),w.destroy($)}})}function TH(w,$,Y,A,X,J,U){let j=`${w} ${$} HTTP/1.1\r
|
|
223
223
|
host: ${A}\r
|
|
224
224
|
x-forwarded-for: 127.0.0.1\r
|
|
225
225
|
x-forwarded-proto: https\r
|
|
@@ -229,7 +229,7 @@ x-forwarded-host: ${X}\r
|
|
|
229
229
|
`}if(j+=`connection: keep-alive\r
|
|
230
230
|
`,U&&!W)j+=`content-length: ${U.length}\r
|
|
231
231
|
`;return j+=`\r
|
|
232
|
-
`,WH.encode(j)}async function NH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:j}=await $.read();if(U)break;if(j){if(A+=j.length,A>M2)return $.cancel().catch(()=>{}),null;Y.push(j)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var rq,VY,q8,tq,Kj,b$,M2=1048576,Ej=30000,YH=16384,y2=262144,AH=2097152,XH=524288,JH=8192,UH=4096,WH,I2,jH,H8;var O2=s(()=>{({connect:rq}=Bun),VY=Symbol("rpx.pool.fallback"),q8=Symbol("rpx.pool.stale"),tq=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Kj=Symbol("rpx.pool.timeout"),b$=Symbol("rpx.pool.busy");WH=new TextEncoder,I2=new TextDecoder,jH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);H8=new Map});function h2(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 _2(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as Ew from"node:path";function R8(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 HH(w){let $=Ew.extname(w).toLowerCase();return qH[$]??"application/octet-stream"}function RH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=Ew.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function MH(w,$){let Y=RH(w);if(Y===null)return null;let A=Ew.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ew.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:Ew.join($.dir,Y,"index.html")};if(A!=="")return{filePath:Ew.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:Ew.join($.dir,`${Y}.html`)};return{filePath:Ew.join($.dir,Y,"index.html")}}async function D2(w,$){let Y=MH(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":HH(Y.filePath),"Cache-Control":A}});if($.spa){let J=Ew.join($.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var qH;var M8=s(()=>{qH={".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 yH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function CH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function Z2(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function x2(w){if(w.upstreamPool)return T2(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function k2(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?Z2(w,$.basePath):w,j=Yj(U,$.pathRewrites);if(j)X=j.targetHost,U=j.targetPath,E("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function VH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function LY(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:j}=VH(X.url),W=CH(X),Q=w(W,U);if(!Q&&Y){let F=await Y(W,U,X);if(F instanceof Response)return F;if(F&&F.retry)Q=w(W,U)}if(!Q)return E("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(Q.auth){let F=H2(X,U,Q.auth);if(F)return E("request",`401 challenge for ${W}${U}`,$),F}if(Q.redirect){let F=_2(Q.redirect,U,j);return E("request",`${Q.redirect.status} redirect ${W}${U} → ${F}`,$),new Response(null,{status:Q.redirect.status,headers:{location:F}})}if(Q.static){let N=Q.stripBasePathPrefix??!0?Z2(U,Q.basePath):U;return D2(N,Q.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let F=x2(Q);if(!J||!F)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:N,targetPath:R}=k2(U,Q,F,$),V=`ws://${N}${R}${j}`,L={};for(let[M,D]of X.headers)if(!IH.has(M.toLowerCase())&&M.toLowerCase()!=="host")L[M]=D;L.host=N,L["x-forwarded-for"]="127.0.0.1",L["x-forwarded-proto"]="https",L["x-forwarded-host"]=W;let q={targetUrl:V,forwardHeaders:L};if(J.upgrade(X,{data:q})){E("ws",`upgraded ${W}${R} → ${V}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let f=x2(Q);if(!f)return new Response(`No upstream configured for ${W}`,{status:502});if(Q.cleanUrls&&U.endsWith(".html")){let F=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:z,targetPath:B}=k2(U,Q,f,$),G=Q.changeOrigin?`http://${z}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",K=Q.upstreamPool;if(K)f.activeConnections++;try{let F=await L2({hostPort:z,method:X.method,path:`${B}${j}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body,signal:X.signal});if(K)T8(K,f);return F}catch(F){if(F===Kj){if(E("request",`Upstream timeout for ${W}`,$),K)MY(K,f);return new Response("Gateway Timeout",{status:504})}if(F===b$)return E("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===VY||!T)try{let N=new Headers(X.headers);if(N.set("host",z),N.set("x-forwarded-for","127.0.0.1"),N.set("x-forwarded-proto","https"),N.set("x-forwarded-host",W),G!==void 0)N.set("origin",G);let R=await fetch(`http://${z}${B}${j}`,{method:X.method,headers:N,body:X.body,redirect:"manual"});if(K)T8(K,f);return R}catch(N){if(E("request",`Proxy error for ${W}: ${N}`,$),K)MY(K,f);return new Response(`Proxy Error: ${N}`,{status:502})}if(E("request",`Proxy error for ${W}: ${F}`,$),K)MY(K,f);return new Response(`Proxy Error: ${F}`,{status:502})}finally{if(K)f.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return E("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function SY(w){let $=new WeakMap,Y=yH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){E("ws",`failed to open upstream ${X}: ${W}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let j={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,j),U.addEventListener("open",()=>{j.upstreamOpen=!0;for(let W of j.pending)U.send(W);j.pending=[],j.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{E("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let j=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+j>Y){E("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=j},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var IH;var Fj=s(()=>{N8();O2();M8();z0();IH=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 i2 from"node:fs";import*as b2 from"node:path";function y8(w,$){if(!w||!$.startsWith(P2))return null;let Y=$.slice(P2.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return i2.readFileSync(b2.join(w,Y),"utf8")}catch{return null}}var P2="/.well-known/acme-challenge/";var Tj=()=>{};function Y$(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function LH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function OY(w){let $=new Map;for(let A of w){let X=Y$(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,j]of X)J.push({path:U,route:j});J.sort((U,j)=>j.path.length-U.path.length),Y.set(A,J)}return Y}function Nj(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!U1(J))continue;if(wY($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}function hY(w,$,Y){let A=Nj(w,$);if(!A)return;for(let X of A)if(LH(Y,X.path))return X.route;return}var I8=()=>{};import*as _Y from"node:fs/promises";import*as qj from"node:path";function u$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}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([_Y.readFile($,"utf8"),_Y.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return E("sni",`skipping ${w}: ${X.message}`,A),null}}async function DY(w,$){let Y=new Map;if(w.certsDir){let X=[];try{X=await _Y.readdir(w.certsDir)}catch(J){E("sni",`certsDir read failed (${w.certsDir}): ${J.message}`,$)}for(let J of X){let U=SH(J);if(!U)continue;let j=J.slice(0,-4);Y.set(U,{certPath:qj.join(w.certsDir,J),keyPath:qj.join(w.certsDir,`${j}.key`)})}}if(w.domains)for(let[X,J]of Object.entries(w.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await OH(X,J.certPath,J.keyPath,$);if(U)A.push(U)}return A}var Hj=s(()=>{z0()});import*as Iw from"node:fs/promises";import*as C8 from"node:path";function xY(w=process.env){let $=w.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if($==="restart"||$==="rebind")return $;return w.INVOCATION_ID?"restart":"rebind"}function DH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function c2(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class i1{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??CX,this.issuer=w.issuer??oU,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??_H;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(!c2(w))return!1;if(DH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return E("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!c2(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return E("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return E("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{E("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),E("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),E("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=u2){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=u2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([Iw.readFile($,"utf8"),Iw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),E("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:C8.join(this.certsDir,`${w}.crt`),keyPath:C8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await Iw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([Iw.writeFile(A,$,"utf8"),Iw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return C8.join(this.certsDir,hH)}async loadAccountKey(){try{return await Iw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await Iw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Iw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var hH="acme-account.key",_H=60000,u2=4096;var Rj=s(()=>{xX();z0()});import*as V8 from"node:net";function y$(w,$,Y){return E("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=V8.createServer(),J=setTimeout(()=>{E("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")E("port",`Port ${w} is in use`,Y),A(!0);else E("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),E("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),E("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function Mj(w,$,Y,A=50){E("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await y$(X,$,Y))return E("port",`Found available port: ${X} after ${J} attempts`,Y),X;E("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function v2(w,$,Y=5000,A){return E("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=V8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{E("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{E("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{E("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class L8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await y$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await v2(w,this.hostname,3000,this.verbose))return E("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await Mj(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await v2(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){E("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var DL;var yj=s(()=>{z0();DL=new L8});import*as S8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as xH}from"node:os";import*as Ij from"node:path";import*as O8 from"node:process";function Aw(){return Ij.join(xH(),".stacks","rpx","registry.d")}function I$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&kH.test(w)}function Cj(w,$){if(!I$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return Ij.join(w,`${$}.json`)}function Xw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return O8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function m2(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&I$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function ZH(w){await p0.mkdir(w,{recursive:!0})}async function b1(w,$=Aw(),Y){if(!m2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await ZH($);let A=Cj($,w.id),X=`${A}.tmp.${O8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),E("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function c$(w,$=Aw(),Y){let A=Cj($,w);try{await p0.unlink(A),E("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function Vj(w,$=Aw(),Y){let A=Cj($,w);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!m2(J))return E("registry",`entry ${w} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return E("registry",`entry ${w} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function Kw(w=Aw(),$){let Y;try{Y=await p0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!I$(J))continue;let U=await Vj(J,w,$);if(U)A.push(U)}return A}async function kY(w=Aw(),$){let Y=await Kw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Xw(X.pid))E("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await c$(X.id,w,$).catch(()=>{}),A++}return A}function h8(w,$={}){let Y=$.dir??Aw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;S8.mkdirSync(Y,{recursive:!0});let U=null,j=!1,W=null,Q=!1,f=(F)=>{return JSON.stringify(F.map((N)=>({id:N.id,from:N.from,to:N.to,path:N.path,pid:N.pid,pathRewrites:N.pathRewrites,cleanUrls:N.cleanUrls,changeOrigin:N.changeOrigin,static:N.static,loadBalancer:N.loadBalancer})).sort((N,R)=>N.id.localeCompare(R.id)))},z=()=>{if(U=null,j)return;Kw(Y,J).then((F)=>{return W=f(F),w(F)}).catch((F)=>{E("registry",`watcher onChange failed: ${F}`,J)})},B=()=>{if(j)return;if(U)clearTimeout(U);U=setTimeout(z,A)},T=setInterval(()=>{if(j||Q)return;Q=!0,Kw(Y,J).then((F)=>{if(f(F)!==W)B()}).catch((F)=>{E("registry",`watcher poll failed: ${F}`,J)}).finally(()=>{Q=!1})},X),K=S8.watch(Y,{persistent:!0},(F,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;B()});return K.on("error",(F)=>{E("registry",`watcher error: ${F}`,J)}),B(),{close:()=>{if(j=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var kH;var v$=s(()=>{z0();kH=/^[a-zA-Z0-9._-]+$/});import{closeSync as g2,openSync as PH,readFileSync as iH}from"node:fs";import*as d2 from"node:fs/promises";import{spawn as bH}from"node:child_process";import{homedir as uH}from"node:os";import*as ZY from"node:path";import*as Cw from"node:process";class Sj{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??Aw(),this.rpxDir=w.rpxDir??ZY.join(uH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??cH,this.pollIntervalMs=w.pollIntervalMs??vH,this.restartDelayMs=w.restartDelayMs??gH,this.killGraceMs=w.killGraceMs??dH,this.launch=w.launcher??lH(this.verbose),this.probePort=w.probePort??nH,this.pickPort=w.pickPort??((Y)=>Mj(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??b1,this.removeEntry=w.removeEntry??c$;let $=w.reapIntervalMs??mH;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let j of w.routes){if($.has(j.portEnv))continue;let W=await this.pickPort(j.defaultPort??3000);$.set(j.portEnv,W)}let Y=ZY.join(this.rpxDir,"sites",`${w.id}.log`);await d2.mkdir(ZY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(j){J=`failed to spawn: ${j.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((j)=>this.onProcessExit(U,j)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((j)=>{E("sites",`readiness loop for ${w.host} threw: ${j}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await Lj(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??Y$(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((W)=>Y$(W.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of $.routes){if(W===A)continue;let Q=Y.get(W.portEnv);if(Q===void 0)continue;J.push({from:Y$(W.path),to:`localhost:${Q}`,stripPrefix:W.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let j=this.now()+2000;while(this.now()<j&&!this.isHostRoutable($.host))await Lj(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Cw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return iH(w.logPath,"utf8").split(`
|
|
232
|
+
`,WH.encode(j)}async function qH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:j}=await $.read();if(U)break;if(j){if(A+=j.length,A>M2)return $.cancel().catch(()=>{}),null;Y.push(j)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var rN,VY,N8,tN,Kj,b$,M2=1048576,Ej=30000,YH=16384,y2=262144,AH=2097152,XH=524288,JH=8192,UH=4096,WH,I2,jH,H8;var O2=s(()=>{({connect:rN}=Bun),VY=Symbol("rpx.pool.fallback"),N8=Symbol("rpx.pool.stale"),tN=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Kj=Symbol("rpx.pool.timeout"),b$=Symbol("rpx.pool.busy");WH=new TextEncoder,I2=new TextDecoder,jH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);H8=new Map});function h2(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 _2(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as Ew from"node:path";function R8(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 HH(w){let $=Ew.extname(w).toLowerCase();return NH[$]??"application/octet-stream"}function RH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=Ew.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function MH(w,$){let Y=RH(w);if(Y===null)return null;let A=Ew.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ew.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:Ew.join($.dir,Y,"index.html")};if(A!=="")return{filePath:Ew.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:Ew.join($.dir,`${Y}.html`)};return{filePath:Ew.join($.dir,Y,"index.html")}}async function D2(w,$){let Y=MH(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":HH(Y.filePath),"Cache-Control":A}});if($.spa){let J=Ew.join($.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var NH;var M8=s(()=>{NH={".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 yH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function CH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function Z2(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function x2(w){if(w.upstreamPool)return T2(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function k2(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?Z2(w,$.basePath):w,j=Yj(U,$.pathRewrites);if(j)X=j.targetHost,U=j.targetPath,E("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function VH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function LY(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:j}=VH(X.url),W=CH(X),Q=w(W,U);if(!Q&&Y){let F=await Y(W,U,X);if(F instanceof Response)return F;if(F&&F.retry)Q=w(W,U)}if(!Q)return E("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(Q.auth){let F=H2(X,U,Q.auth);if(F)return E("request",`401 challenge for ${W}${U}`,$),F}if(Q.redirect){let F=_2(Q.redirect,U,j);return E("request",`${Q.redirect.status} redirect ${W}${U} → ${F}`,$),new Response(null,{status:Q.redirect.status,headers:{location:F}})}if(Q.static){let q=Q.stripBasePathPrefix??!0?Z2(U,Q.basePath):U;return D2(q,Q.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let F=x2(Q);if(!J||!F)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:q,targetPath:R}=k2(U,Q,F,$),V=`ws://${q}${R}${j}`,L={};for(let[M,D]of X.headers)if(!IH.has(M.toLowerCase())&&M.toLowerCase()!=="host")L[M]=D;L.host=q,L["x-forwarded-for"]="127.0.0.1",L["x-forwarded-proto"]="https",L["x-forwarded-host"]=W;let N={targetUrl:V,forwardHeaders:L};if(J.upgrade(X,{data:N})){E("ws",`upgraded ${W}${R} → ${V}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let f=x2(Q);if(!f)return new Response(`No upstream configured for ${W}`,{status:502});if(Q.cleanUrls&&U.endsWith(".html")){let F=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:z,targetPath:B}=k2(U,Q,f,$),G=Q.changeOrigin?`http://${z}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",K=Q.upstreamPool;if(K)f.activeConnections++;try{let F=await L2({hostPort:z,method:X.method,path:`${B}${j}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body,signal:X.signal});if(K)T8(K,f);return F}catch(F){if(F===Kj){if(E("request",`Upstream timeout for ${W}`,$),K)MY(K,f);return new Response("Gateway Timeout",{status:504})}if(F===b$)return E("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===VY||!T)try{let q=new Headers(X.headers);if(q.set("host",z),q.set("x-forwarded-for","127.0.0.1"),q.set("x-forwarded-proto","https"),q.set("x-forwarded-host",W),G!==void 0)q.set("origin",G);let R=await fetch(`http://${z}${B}${j}`,{method:X.method,headers:q,body:X.body,redirect:"manual"});if(K)T8(K,f);return R}catch(q){if(E("request",`Proxy error for ${W}: ${q}`,$),K)MY(K,f);return new Response(`Proxy Error: ${q}`,{status:502})}if(E("request",`Proxy error for ${W}: ${F}`,$),K)MY(K,f);return new Response(`Proxy Error: ${F}`,{status:502})}finally{if(K)f.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return E("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function SY(w){let $=new WeakMap,Y=yH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){E("ws",`failed to open upstream ${X}: ${W}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let j={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,j),U.addEventListener("open",()=>{j.upstreamOpen=!0;for(let W of j.pending)U.send(W);j.pending=[],j.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{E("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let j=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+j>Y){E("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=j},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var IH;var Fj=s(()=>{q8();O2();M8();z0();IH=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 i2 from"node:fs";import*as b2 from"node:path";function y8(w,$){if(!w||!$.startsWith(P2))return null;let Y=$.slice(P2.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return i2.readFileSync(b2.join(w,Y),"utf8")}catch{return null}}var P2="/.well-known/acme-challenge/";var Tj=()=>{};function Y$(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function LH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function OY(w){let $=new Map;for(let A of w){let X=Y$(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,j]of X)J.push({path:U,route:j});J.sort((U,j)=>j.path.length-U.path.length),Y.set(A,J)}return Y}function qj(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!U1(J))continue;if(wY($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}function hY(w,$,Y){let A=qj(w,$);if(!A)return;for(let X of A)if(LH(Y,X.path))return X.route;return}var I8=()=>{};import*as _Y from"node:fs/promises";import*as Nj from"node:path";function u$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}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([_Y.readFile($,"utf8"),_Y.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return E("sni",`skipping ${w}: ${X.message}`,A),null}}async function DY(w,$){let Y=new Map,A=w.certsDirServerNames?new Set(w.certsDirServerNames):void 0;if(w.certsDir){let J=[];try{J=await _Y.readdir(w.certsDir)}catch(U){E("sni",`certsDir read failed (${w.certsDir}): ${U.message}`,$)}for(let U of J){let j=SH(U);if(!j)continue;if(A&&!A.has(j))continue;let W=U.slice(0,-4);Y.set(j,{certPath:Nj.join(w.certsDir,U),keyPath:Nj.join(w.certsDir,`${W}.key`)})}}if(w.domains)for(let[J,U]of Object.entries(w.domains))Y.set(J,U);let X=[];for(let[J,U]of Y){let j=await OH(J,U.certPath,U.keyPath,$);if(j)X.push(j)}return X}var Hj=s(()=>{z0()});import*as Iw from"node:fs/promises";import*as C8 from"node:path";function xY(w=process.env){let $=w.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if($==="restart"||$==="rebind")return $;return w.INVOCATION_ID?"restart":"rebind"}function DH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function c2(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class i1{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??CX,this.issuer=w.issuer??oU,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??_H;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(!c2(w))return!1;if(DH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return E("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!c2(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return E("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return E("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{E("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),E("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),E("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=u2){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=u2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([Iw.readFile($,"utf8"),Iw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),E("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:C8.join(this.certsDir,`${w}.crt`),keyPath:C8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await Iw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([Iw.writeFile(A,$,"utf8"),Iw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return C8.join(this.certsDir,hH)}async loadAccountKey(){try{return await Iw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await Iw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Iw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var hH="acme-account.key",_H=60000,u2=4096;var Rj=s(()=>{xX();z0()});import*as V8 from"node:net";function y$(w,$,Y){return E("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=V8.createServer(),J=setTimeout(()=>{E("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")E("port",`Port ${w} is in use`,Y),A(!0);else E("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),E("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),E("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function Mj(w,$,Y,A=50){E("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await y$(X,$,Y))return E("port",`Found available port: ${X} after ${J} attempts`,Y),X;E("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function v2(w,$,Y=5000,A){return E("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=V8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{E("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{E("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{E("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class L8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await y$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await v2(w,this.hostname,3000,this.verbose))return E("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await Mj(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await v2(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){E("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var DL;var yj=s(()=>{z0();DL=new L8});import*as S8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as xH}from"node:os";import*as Ij from"node:path";import*as O8 from"node:process";function Aw(){return Ij.join(xH(),".stacks","rpx","registry.d")}function I$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&kH.test(w)}function Cj(w,$){if(!I$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return Ij.join(w,`${$}.json`)}function Xw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return O8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function m2(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&I$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function ZH(w){await p0.mkdir(w,{recursive:!0})}async function b1(w,$=Aw(),Y){if(!m2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await ZH($);let A=Cj($,w.id),X=`${A}.tmp.${O8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),E("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function c$(w,$=Aw(),Y){let A=Cj($,w);try{await p0.unlink(A),E("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function Vj(w,$=Aw(),Y){let A=Cj($,w);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!m2(J))return E("registry",`entry ${w} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return E("registry",`entry ${w} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function Kw(w=Aw(),$){let Y;try{Y=await p0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!I$(J))continue;let U=await Vj(J,w,$);if(U)A.push(U)}return A}async function kY(w=Aw(),$){let Y=await Kw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Xw(X.pid))E("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await c$(X.id,w,$).catch(()=>{}),A++}return A}function h8(w,$={}){let Y=$.dir??Aw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;S8.mkdirSync(Y,{recursive:!0});let U=null,j=!1,W=null,Q=!1,f=(F)=>{return JSON.stringify(F.map((q)=>({id:q.id,from:q.from,to:q.to,path:q.path,pid:q.pid,pathRewrites:q.pathRewrites,cleanUrls:q.cleanUrls,changeOrigin:q.changeOrigin,static:q.static,loadBalancer:q.loadBalancer})).sort((q,R)=>q.id.localeCompare(R.id)))},z=()=>{if(U=null,j)return;Kw(Y,J).then((F)=>{return W=f(F),w(F)}).catch((F)=>{E("registry",`watcher onChange failed: ${F}`,J)})},B=()=>{if(j)return;if(U)clearTimeout(U);U=setTimeout(z,A)},T=setInterval(()=>{if(j||Q)return;Q=!0,Kw(Y,J).then((F)=>{if(f(F)!==W)B()}).catch((F)=>{E("registry",`watcher poll failed: ${F}`,J)}).finally(()=>{Q=!1})},X),K=S8.watch(Y,{persistent:!0},(F,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;B()});return K.on("error",(F)=>{E("registry",`watcher error: ${F}`,J)}),B(),{close:()=>{if(j=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var kH;var v$=s(()=>{z0();kH=/^[a-zA-Z0-9._-]+$/});import{closeSync as g2,openSync as PH,readFileSync as iH}from"node:fs";import*as d2 from"node:fs/promises";import{spawn as bH}from"node:child_process";import{homedir as uH}from"node:os";import*as ZY from"node:path";import*as Cw from"node:process";class Sj{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??Aw(),this.rpxDir=w.rpxDir??ZY.join(uH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??cH,this.pollIntervalMs=w.pollIntervalMs??vH,this.restartDelayMs=w.restartDelayMs??gH,this.killGraceMs=w.killGraceMs??dH,this.launch=w.launcher??lH(this.verbose),this.probePort=w.probePort??nH,this.pickPort=w.pickPort??((Y)=>Mj(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??b1,this.removeEntry=w.removeEntry??c$;let $=w.reapIntervalMs??mH;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let j of w.routes){if($.has(j.portEnv))continue;let W=await this.pickPort(j.defaultPort??3000);$.set(j.portEnv,W)}let Y=ZY.join(this.rpxDir,"sites",`${w.id}.log`);await d2.mkdir(ZY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(j){J=`failed to spawn: ${j.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((j)=>this.onProcessExit(U,j)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((j)=>{E("sites",`readiness loop for ${w.host} threw: ${j}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await Lj(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??Y$(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((W)=>Y$(W.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of $.routes){if(W===A)continue;let Q=Y.get(W.portEnv);if(Q===void 0)continue;J.push({from:Y$(W.path),to:`localhost:${Q}`,stripPrefix:W.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let j=this.now()+2000;while(this.now()<j&&!this.isHostRoutable($.host))await Lj(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Cw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return iH(w.logPath,"utf8").split(`
|
|
233
233
|
`).slice(-$).join(`
|
|
234
234
|
`).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),Lj(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)E("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function Lj(w){return new Promise(($)=>setTimeout($,w))}async function nH(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 lH(w){let $=pH();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=PH(J,"a");try{let j=bH("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),W=j.pid;if(W===void 0)throw Error("spawn returned no pid");let Q=new Promise((f)=>{j.once("exit",(z)=>{f(z)}),j.once("error",()=>{f(null)})}).finally(()=>{try{g2(U)}catch{}});return E("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,w),{pid:W,exited:Q,stop:(f="SIGTERM")=>{try{Cw.kill(-W,f)}catch{try{j.kill(f)}catch{}}}}}catch(j){try{g2(U)}catch{}throw j}}}function pH(){if(Cw.platform==="win32")return null;if(!(typeof Cw.getuid==="function"&&Cw.getuid()===0))return null;let $=Number.parseInt(Cw.env.SUDO_UID??"",10),Y=Number.parseInt(Cw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var cH=120000,vH=200,mH=30000,gH=3000,dH=4000;var n2=s(()=>{I8();yj();v$();z0();_$()});function u1(w){return w.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function l2(w,$,Y){return`<!doctype html>
|
|
235
235
|
<html lang="en">
|
|
@@ -292,9 +292,9 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
|
|
|
292
292
|
nameserver 127.0.0.1
|
|
293
293
|
port ${vY}
|
|
294
294
|
`}function c1(w){return j6.join(f6,w)}function K6(w){return w.includes("127.0.0.1")&&w.includes(String(vY))}async function fR(w){try{return await W6.readFile(c1(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function uj(w){if(X$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),k1));if(!A()&&!Y()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",w)}catch(X){E("dns",`Could not flush DNS cache: ${X}`,w)}}function F6(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function zR(w,$){F6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (z0(),k1)),A=QR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${f6} && printf "%b" "${A}" > ${c1(w)}'`;Y(X),E("dns",`Created ${c1(w)}`,$)}async function BR(w,$){F6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (z0(),k1));Y(`rm -f ${c1(w)}`),E("dns",`Removed ${c1(w)}`,$)}async function GR(w,$){return mj({domains:$??[],verbose:w})}async function ER(w,$){if(X$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),k1));if(!A()&&!Y())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await zR(X,$);return await uj($),!0}catch(X){return E("dns",`Failed to create resolver file: ${X}`,$),!1}}async function cj(w,$){if(X$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),k1));if(!A()&&!Y())return;try{for(let X of w)await BR(X,$);await uj($)}catch(X){E("dns",`Failed to remove resolver files: ${X}`,$)}}async function vj(w){if(X$.platform!=="darwin")return[];let $=[];for(let Y of $6){let A=await fR(Y);if(A&&K6(A))await cj([Y],w),$.push(Y)}return $}async function mj(w){let $=w.rpxDir??V0(),Y=ij(w.domains);if(Y.length===0)return!1;let A=Pj(Y),X=await G6(Y,w.verbose);if(!X){let j=Y[0];if(j&&await E6(j))X=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await ER(A,w.verbose))return!1;let U={version:k8,resolvers:A,domains:Y,ownerPid:w.ownerPid??X$.pid,updatedAt:new Date().toISOString()};return await A6($,U),!0}async function v1(w,$={}){let Y=w.map((W)=>W.to).filter(Boolean),A=$.rpxDir??V0(),X=Pj(Y),j=((await Z8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(j.length>0)await cj(j,$.verbose);if(X.length===0){bj($.verbose),await Zj(A);return}await mj({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??X$.pid})}async function g$(w={}){let $=w.rpxDir??V0();bj(w.verbose);let A=(await Z8($))?.resolvers??[];await cj(A,w.verbose),await vj(w.verbose),await Zj($)}async function KR(w){await g$({verbose:w})}async function d$(w={}){let $=w.rpxDir??V0(),Y=await Z8($),A=Y?.ownerPid!=null&&Xw(Y.ownerPid);if(Y&&!A){E("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await g$(w);return}let X=await vj(w.verbose);if(X.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await uj(w.verbose)}var vY=15353,Q6="# managed-by: rpx",f6="/etc/resolver",t0=null,P8;var mY=s(()=>{b8();J6();v$();z0();P8=new Set});import{spawn as H6}from"node:child_process";import*as i0 from"node:fs/promises";import{homedir as R6}from"node:os";import*as hw from"node:path";import*as I from"node:process";function V0(){return hw.join(R6(),".stacks","rpx")}function L$(w=V0()){return hw.join(w,"daemon.pid")}async function V$(w=V0()){try{let $=await i0.readFile(L$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function m8(w=V0()){let $=await V$(w);return $!==null&&Xw($)}async function M6(w=V0()){await i0.mkdir(w,{recursive:!0});let $=L$(w);while(!0){try{let A=await i0.open($,"wx");try{await A.write(`${I.pid}
|
|
295
|
-
`)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await V$(w);if(Y!==null&&Xw(Y))throw Error(`rpx daemon already running (pid=${Y})`);await i0.unlink($).catch(()=>{})}}async function m1(w=V0()){await i0.unlink(L$(w)).catch(()=>{})}function v8(w){for(let[$,Y]of c8)if(!w.has($))P1(Y),c8.delete($)}function TR(w,$){let Y=F2($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function y6(w){let $=w.cleanUrls??!1,Y=Y$(w.path),A=CY(w.auth);if(w.static)return{static:R8(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=i$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),j=c8.get(w.id);if(j&&!TR(j,X))P1(j),j=void 0;if(!j)j=RY(X,w.loadBalancer),yY(j),c8.set(w.id,j);return{sourceHost:U.host,upstreamPool:j,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function
|
|
296
|
-
`),Q.stdin.end();Q.unref();let B=L$(w),G=Date.now()+15000;while(Date.now()<G){if(f)throw f;let T=await V$(w);if(T!==null&&Xw(T)){if(A)H.success(`rpx daemon elevated to root (pid=${T}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:B,done:Promise.resolve(),stop:async()=>{try{I.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${$} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((K)=>setTimeout(K,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${w})`)}function gj(){if(T6)return;T6=!0,I.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),I.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function I6(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=y8(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 C6(w={}){gj();let $=w.verbose??!1,Y=w.rpxDir??V0(),A=w.registryDir??hw.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"::",j=w.hostname==null,W=w.gcIntervalMs??FR;if(I.env.RPX_DAEMON_WORKER==="1")return MR({rpxDir:I.env.RPX_WORKER_RPXDIR??Y,registryDir:I.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(I.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:I.env.RPX_WORKER_HOSTNAME??U,verbose:I.env.RPX_WORKER_VERBOSE==="1"||$});let Q=X>0&&X<1024||J>0&&J<1024,f=typeof I.getuid==="function"&&I.getuid()===0;if(I.platform!=="win32"&&Q&&!f)return
|
|
297
|
-
`):B.ca}:null,T=!1,K=[];function F(_){for(let u0 of K)try{u0.kill(_)}catch{}}async function N(_){await N6(Y,_,G),F("SIGHUP")}let R=w.onDemandTls,V=R?.enabled?new i1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:z,verbose:j,onCertAdded:(_)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",j),setTimeout(()=>I.kill(I.pid,"SIGTERM"),10).unref();else N(_)}}):null;await N6(Y,V?V.sniEntries():z,G);let L=await Kw(A,j);await d$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS reconcile on start failed: ${_}`,j)}),await v1(L,{rpxDir:Y,verbose:j,ownerPid:I.pid}).catch((_)=>{E("daemon",`DNS setup on start failed: ${_}`,j)}),await kY(A,j).catch(()=>{}),await uY({verbose:j}).catch(()=>{});let q=h8((_)=>{v1(_,{rpxDir:Y,verbose:j,ownerPid:I.pid}).catch((u0)=>{E("daemon",`DNS sync on registry change failed: ${u0}`,j)})},{dir:A,verbose:j}),C=setInterval(()=>{kY(A,j).catch(()=>{}),uY({verbose:j}).catch(()=>{})},W);C.unref?.();let M=null;if(J>0)M=Bun.serve({port:J,hostname:U,fetch(_){return I6(_,V,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,n=60000,r0=30000,Jw=0,n$=Date.now();function g1(){if(T)return;let _={...I.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:j?"1":"0"},u0=Bun.spawn(RR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(d1,pY){if(T)return;let rY=K.indexOf(d1);if(rY!==-1)K.splice(rY,1);let l$=Date.now();if(l$-n$>n)n$=l$,Jw=0;if(Jw++,Jw>D){H.error(`rpx: worker keeps exiting (code ${pY}); giving up after ${D} restarts in ${Math.round(n/1000)}s`);return}let Sw=Math.min(r0,100*2**Math.min(Jw,8));E("daemon",`worker exited (code ${pY}); respawning in ${Sw}ms (restart ${Jw}/${D})`,j),setTimeout(g1,Sw).unref?.()}});K.push(u0)}for(let _=0;_<Q;_++)g1();if(j)H.success(`rpx coordinator listening on https://${U}:${X} via ${Q} worker(s)${M?` (http→https on :${J})`:""}`),H.info(`pid file: ${f}`);let J$,a0=new Promise((_)=>{J$=_});async function Vw(){if(T)return a0;if(T=!0,clearInterval(C),q.close(),M?.stop(!1),F("SIGTERM"),await Promise.race([Promise.all(K.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),F("SIGKILL"),await g$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS teardown failed: ${_}`,j)}),await m1(Y),await i0.unlink(dj(Y)).catch(()=>{}),j)H.info("rpx coordinator stopped");return J$(),a0}let Lw=(_)=>{E("daemon",`coordinator received ${_}, shutting down`,j),Vw().catch(()=>{})};return I.once("SIGINT",Lw),I.once("SIGTERM",Lw),{stop:Vw,done:a0,httpsPort:X,httpPort:J,pidPath:f,ensureCert:(_)=>V?V.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function IR(){let w=I.execPath,$=hw.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&I.argv[1])return[w,I.argv[1],"daemon:start"];return[w,"daemon:start"]}async function g8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await d$({rpxDir:$,verbose:Y}).catch((f)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${f}`,Y)});let A=await V$($);if(A!==null&&Xw(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await m1($);await i0.mkdir($,{recursive:!0});let X=w.spawnCommand??IR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=H6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??I.cwd(),env:w.spawnEnv?{...I.env,...w.spawnEnv}:I.env});J.unref();let U=null;J.once("error",(f)=>{U=f});let j=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,Q=Date.now()+j;while(Date.now()<Q){if(U)throw U;let f=await V$($);if(f!==null&&Xw(f))return E("daemon",`daemon registered with pid=${f}`,Y),{pid:f,spawned:!0};await new Promise((z)=>setTimeout(z,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${j}ms (rpxDir=${$})`)}async function V6(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await V$($);if(U===null||!Xw(U)){if(U!==null)await m1($);return await d$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{I.kill(U,"SIGTERM")}catch(W){let Q=W.code;if(Q==="ESRCH")return await m1($),{stopped:!1,pid:U,forced:!1};if(Q==="EPERM")T$(`kill -TERM ${U}`);else throw W}let j=Date.now()+A;while(Date.now()<j){if(!Xw(U))return E("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);E("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{I.kill(U,"SIGKILL")}catch(W){let Q=W.code;if(Q==="EPERM")T$(`kill -KILL ${U}`);else if(Q!=="ESRCH")throw W}return await m1($),await g$({rpxDir:$,verbose:Y}).catch((W)=>{E("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function L6(w={}){let $=w.rpxDir??V0();if(await m8($))return;await d$({rpxDir:$,verbose:w.verbose})}var FR=5000,c8,T6=!1;var b8=s(()=>{_$();Gj();Fj();Tj();I8();Hj();Rj();QU();n2();M8();N8();v$();Dj();mY();z0();c8=new Map});import{dirname as bR,join as uR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as cR}from"node:url";import{existsSync as t6}from"node:fs";import JJ from"node:fs/promises";import wQ from"node:os";import UJ from"node:path";import S$ from"node:process";import{EventEmitter as a6}from"node:events";import U$ from"node:process";import $Q from"node:process";import fJ from"node:process";import sY from"node:process";import r1 from"node:process";import XQ from"node:tty";import iG,{stdin as UM,stdout as WM}from"node:process";import UQ,{stdin as cG,stdout as vG}from"node:process";import mG from"node:readline";class jQ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=wQ.homedir(),$=UJ.join(w,".config","clapp");this.configPath=UJ.join($,"telemetry.json")}async isEnabled(){if(S$.env.DO_NOT_TRACK==="1"||S$.env.DO_NOT_TRACK==="true")return!1;if(S$.env.NO_TELEMETRY==="1"||S$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:wQ.platform(),nodeVersion:S$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:S$.env.DO_NOT_TRACK==="1"||S$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(t6(this.configPath)){let w=await JJ.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 $=UJ.dirname(this.configPath);await JJ.mkdir($,{recursive:!0}),await JJ.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 rR=new jQ;function s6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let j of Object.keys(A))for(let W of A[j])J[W]=j;for(let j of X)if(A[j])for(let W of A[j])X.add(W);function U(j,W){let Q=J[j]||j;if(Y[Q]=W,A[Q])for(let f of A[Q])Y[f]=W;if(J[j]&&A[J[j]])for(let f of A[J[j]])Y[f]=W;Y[j]=W}for(let j=0;j<w.length;j++){let W=w[j];if(W==="--"){Y._.push(...w.slice(j+1));break}if(W.startsWith("--")){let Q=W.indexOf("=");if(Q!==-1){let f=W.slice(2,Q),z=W.slice(Q+1);U(f,z)}else{let f=W.slice(2);if(f.startsWith("no-")){let B=f.slice(3);U(B,!1);continue}let z=J[f]||f;if(X.has(z)||X.has(f))U(f,!0);else{let B=w[j+1];if(B!==void 0&&!B.startsWith("-"))U(f,B),j++;else U(f,!0)}}}else if(W.startsWith("-")&&W.length>1){let Q=W.slice(1);for(let f=0;f<Q.length;f++){let z=Q[f],B=J[z]||z;if(f===Q.length-1&&!X.has(B)&&!X.has(z)){let G=w[j+1];if(G!==void 0&&!G.startsWith("-"))U(z,G),j++;else U(z,!0)}else U(z,!0)}}else Y._.push(W)}return Y}function QJ(w){return w.replace(/[<[].+/,"").trim()}function o6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(j)=>{let W=!1,Q=j[1];if(Q.startsWith("..."))Q=Q.slice(3),W=!0;return{required:j[0].startsWith("<"),value:Q,variadic:W}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function e6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((j)=>A.names.includes(j))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function YQ(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function WJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function wG(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function $G(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 YG(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 AG(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function QQ(w){return w.split(".").map(($,Y)=>{return Y===0?wG($):$}).join(".")}class aY 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}
|
|
295
|
+
`)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await V$(w);if(Y!==null&&Xw(Y))throw Error(`rpx daemon already running (pid=${Y})`);await i0.unlink($).catch(()=>{})}}async function m1(w=V0()){await i0.unlink(L$(w)).catch(()=>{})}function v8(w){for(let[$,Y]of c8)if(!w.has($))P1(Y),c8.delete($)}function TR(w,$){let Y=F2($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function y6(w){let $=w.cleanUrls??!1,Y=Y$(w.path),A=CY(w.auth);if(w.static)return{static:R8(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=i$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),j=c8.get(w.id);if(j&&!TR(j,X))P1(j),j=void 0;if(!j)j=RY(X,w.loadBalancer),yY(j),c8.set(w.id,j);return{sourceHost:U.host,upstreamPool:j,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function qR(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function u8(w,$,Y=[],A=!1){let X=await Kw($,w.verbose),J=[...new Set([...X.map((f)=>f.to).filter(Boolean),...Y])],U=qR(J),j=[...new Set([U,...J,"rpx.localhost"])],W=z2(J,U,w.verbose);if(typeof w.https==="object"&&typeof W.https==="object")W.https={...W.https,...w.https};let Q=await M$(W);if(Q&&(A||!qW(zj,j)))E("daemon",`regenerating shared cert for host(s): ${j.join(", ")}`,w.verbose),Bj(),Q=null;if(!Q)E("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await NY({...W,forceRegenerate:!0}),Q=await M$(W);if(!Q)throw Error("failed to bootstrap TLS for rpx daemon");return Q}async function NR(w,$,Y,A){let X=I.env.SUDO_PASSWORD,J=I.env.HOME??R6(),U=[I.execPath,...I.argv.slice(1)],j=[`HOME=${J}`,`PATH=${I.env.PATH??""}`];if(A)j.push("RPX_VERBOSE=1");for(let[T,K]of Object.entries(I.env))if(K!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))j.push(`${T}=${K}`);let W=X?["-S","-p","","env",...j,...U]:["-n","env",...j,...U];E("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let Q=H6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),f=null,z=null;if(Q.once("error",(T)=>{f=T}),Q.once("exit",(T)=>{z=T??0}),X&&Q.stdin)Q.stdin.write(`${X}
|
|
296
|
+
`),Q.stdin.end();Q.unref();let B=L$(w),G=Date.now()+15000;while(Date.now()<G){if(f)throw f;let T=await V$(w);if(T!==null&&Xw(T)){if(A)H.success(`rpx daemon elevated to root (pid=${T}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:B,done:Promise.resolve(),stop:async()=>{try{I.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${$} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((K)=>setTimeout(K,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${w})`)}function gj(){if(T6)return;T6=!0,I.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),I.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function I6(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=y8(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 C6(w={}){gj();let $=w.verbose??!1,Y=w.rpxDir??V0(),A=w.registryDir??hw.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"::",j=w.hostname==null,W=w.gcIntervalMs??FR;if(I.env.RPX_DAEMON_WORKER==="1")return MR({rpxDir:I.env.RPX_WORKER_RPXDIR??Y,registryDir:I.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(I.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:I.env.RPX_WORKER_HOSTNAME??U,verbose:I.env.RPX_WORKER_VERBOSE==="1"||$});let Q=X>0&&X<1024||J>0&&J<1024,f=typeof I.getuid==="function"&&I.getuid()===0;if(I.platform!=="win32"&&Q&&!f)return NR(Y,X,J,$);let z=Math.max(1,w.workers??(Number.parseInt(I.env.RPX_WORKERS??"",10)||1));if(z>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return yR(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:W,workers:z})}let B=await M6(Y),G=new Map,T=(y,h)=>hY(G,y,h);function K(y){G=OY(y.map((s0)=>({host:s0.to,path:s0.path,route:y6(s0)}))),v8(new Set(y.map((s0)=>s0.id)));let h=Array.from(G.keys());E("daemon",`routing table now covers ${h.length} host(s): ${h.join(", ")||"<empty>"}`,$)}await kY(A,$).catch((y)=>{E("daemon",`initial gc failed: ${y}`,$)}),await uY({verbose:$}).catch((y)=>{E("daemon",`stale hosts GC on start failed: ${y}`,$)});let F=await Kw(A,$);K(F),await d$({rpxDir:Y,verbose:$}).catch((y)=>{E("daemon",`DNS reconcile on start failed: ${y}`,$)}),await v1(F,{rpxDir:Y,verbose:$,ownerPid:I.pid}).catch((y)=>{E("daemon",`DNS setup on start failed: ${y}`,$)});let q=[];if(w.productionCerts){if(q=await DY(w.productionCerts,$),$&&q.length>0)H.info(`SNI: serving ${q.length} real cert(s): ${q.map((y)=>y.serverName).join(", ")}`)}let R=new Set,V=null,L;if(w.onDemandSites?.enabled){if(V=new Sj({resolver:jU(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(y)=>qj(G,y)!==void 0,onSiteActivating:(y)=>{pY(y)}}),L=async(y)=>{let h=await V.onRequest(y);switch(h.kind){case"ready":return{retry:!0};case"starting":return p2({host:h.host,sinceMs:h.sinceMs,logTail:h.logTail});case"failed":return r2({host:h.host,error:h.error,logTail:h.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let N=LY(T,$,L),C=SY($),M=null;if(q.length===0)M=await u8(w,A);let D=w.onDemandTls,n=D?.enabled?new i1({config:D,certsDir:D.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:q,verbose:$,onCertAdded:(y)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",$),setTimeout(()=>I.kill(I.pid,"SIGTERM"),10).unref();else _(y)}}):null;function r0(y){if(y.length>0)return u$(y.map((h)=>({serverName:h.serverName,cert:h.cert,key:h.key})));return u$({key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1})}function Jw(y){try{return Bun.serve(y)}catch(h){let s0=h instanceof Error?h.message:String(h),n1=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(s0);if(!j||y.hostname!=="::"||!n1)throw h;return E("daemon",`no IPv6 on this host (${s0}); binding 0.0.0.0`,w.verbose),Bun.serve({...y,hostname:"0.0.0.0"})}}function n$(y){return Jw({port:X,hostname:U,reusePort:TY(),tls:r0(y),fetch(h,s0){return N(h,s0)},websocket:C,error(h){return E("daemon",`https server error: ${h}`,$),new Response(`Server Error: ${h.message}`,{status:500})}})}let g1=(y)=>[...new Set(y.map((h)=>h.to).filter(Boolean))],J$=(y)=>{if(!M)return q;return f2([...g1(y),...R,"rpx.localhost"],M)},a0=n$(n?n.sniEntries():q.length>0?q:J$(F)),Vw=null,Lw=!1;async function _(y){if(Sw)return;if(Vw=y,Lw)return;Lw=!0;try{while(!Sw&&Vw){let h=Vw;Vw=null,E("daemon",`rebuilding :443 with ${h.length} SNI cert(s)`,$),a0.stop(!1);let s0,n1=!1,oj=60,m6=500;for(let XJ=0;!Sw&&!n1;XJ++)try{a0=n$(h),n1=!0;break}catch(g6){if(s0=g6,XJ>=oj)break;await new Promise((d6)=>setTimeout(d6,Math.min(25*2**Math.min(XJ,4),m6)))}if(!n1)H.error(`rpx: CRITICAL — could not rebind :443 after ${oj} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${s0?.message}`)}}finally{Lw=!1}}let u0=null;if(J>0)u0=Jw({port:J,hostname:U,fetch(y){return I6(y,n,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${u0?` (http→https on :${J})`:""}`),H.info(`pid file: ${B}`),H.info(`registry: ${A}`);async function d1(y){if(Sw||q.length>0||n||!M)return;try{M=await u8(w,A,[...R]),await _(J$(y))}catch(h){E("daemon",`TLS sync on registry change failed: ${h}`,$)}}async function pY(y){if(Sw||q.length>0||n||!M||!y)return;if(R.has(y))return;R.add(y);try{M=await u8(w,A,[...R],!0);let h=await Kw(A,$);await _(J$(h))}catch(h){E("daemon",`dev cert refresh for ${y} failed: ${h}`,$)}}let rY=h8((y)=>{K(y),d1(y),v1(y,{rpxDir:Y,verbose:$,ownerPid:I.pid}).catch((h)=>{E("daemon",`DNS sync on registry change failed: ${h}`,$)})},{dir:A,verbose:$}),l$=setInterval(()=>{kY(A,$).then((y)=>{if(y>0)E("daemon",`gc reaped ${y} stale entries`,$)}).catch((y)=>{E("daemon",`periodic gc failed: ${y}`,$)}),uY({verbose:$}).then((y)=>{if(y.length>0)E("daemon",`gc reaped stale hosts entries: ${y.join(", ")}`,$)}).catch((y)=>{E("daemon",`periodic hosts gc failed: ${y}`,$)})},W);if(typeof l$.unref==="function")l$.unref();let Sw=!1,YJ,AJ=new Promise((y)=>{YJ=y});async function aj(){if(Sw)return AJ;if(Sw=!0,clearInterval(l$),rY.close(),await V?.stopAll().catch((y)=>{E("daemon",`site supervisor stopAll failed: ${y}`,$)}),a0.stop(!1),u0?.stop(!1),await g$({rpxDir:Y,verbose:$}).catch((y)=>{E("daemon",`DNS teardown failed: ${y}`,$)}),v8(new Set),await m1(Y),$)H.info("rpx daemon stopped");return YJ(),AJ}let sj=(y)=>{E("daemon",`received ${y}, shutting down`,$),aj().catch(()=>{})};return I.once("SIGINT",sj),I.once("SIGTERM",sj),{stop:aj,done:AJ,httpsPort:typeof a0.port==="number"?a0.port:X,httpPort:u0&&typeof u0.port==="number"?u0.port:J,pidPath:B,ensureCert:(y)=>n?n.ensureCert(y):Promise.resolve(!1),listSites:()=>V?.list()??[]}}function dj(w){return hw.join(w,"cluster-sni.json")}async function q6(w,$,Y){let A=dj(w),X=`${A}.${I.pid}.tmp`;await i0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await i0.rename(X,A)}async function N6(w){try{return JSON.parse(await i0.readFile(dj(w),"utf8"))}catch{return{sni:[],dev:null}}}function HR(w){if(w.sni.length>0)return u$(w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key})));if(w.dev)return u$({key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function RR(){let w=I.execPath,$=I.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=hw.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&I.argv[1])return[w,I.argv[1],"daemon:start"];return[w,"daemon:start"]}async function MR(w){gj();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,j=(C,M)=>hY(U,C,M),W=(C)=>{U=OY(C.map((M)=>({host:M.to,path:M.path,route:y6(M)}))),v8(new Set(C.map((M)=>M.id)))};W(await Kw(Y,J));let Q=LY(j,J),f=SY(J),z=!1,B=(C)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:HR(C),fetch(M,D){return Q(M,D)},websocket:f,error(M){return E("daemon",`worker https error: ${M}`,J),new Response(`Server Error: ${M.message}`,{status:500})}}),G=B(await N6($));async function T(){if(z)return;let C=await N6($),M=null;for(let n=0;n<20&&!z;n++)try{M=B(C);break}catch{await new Promise((r0)=>setTimeout(r0,25))}if(!M){E("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let D=G;G=M,D.stop(!1)}let K=h8((C)=>W(C),{dir:Y,verbose:J}),F=()=>{T().catch(()=>{})};I.on("SIGHUP",F);let q=()=>{let C=I.removeListener??I.off;if(typeof C==="function")C.call(I,"SIGHUP",F)},R,V=new Promise((C)=>{R=C});async function L(){if(z)return V;return z=!0,q(),K.close(),G.stop(!1),v8(new Set),R(),V}let N=()=>{L().then(()=>I.exit(0)).catch(()=>I.exit(0))};if(I.once("SIGTERM",N),I.once("SIGINT",N),J)H.success(`rpx worker (pid ${I.pid}) serving :${A}`);return{stop:L,done:V,httpsPort:typeof G.port==="number"?G.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function yR(w,$){gj();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:j,gcIntervalMs:W,workers:Q}=$,f=await M6(Y),z=[];if(w.productionCerts)z=await DY(w.productionCerts,j);let B=null;if(z.length===0)B=await u8(w,A);let G=B?{key:B.key,cert:B.cert,ca:Array.isArray(B.ca)?B.ca.join(`
|
|
297
|
+
`):B.ca}:null,T=!1,K=[];function F(_){for(let u0 of K)try{u0.kill(_)}catch{}}async function q(_){await q6(Y,_,G),F("SIGHUP")}let R=w.onDemandTls,V=R?.enabled?new i1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:z,verbose:j,onCertAdded:(_)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",j),setTimeout(()=>I.kill(I.pid,"SIGTERM"),10).unref();else q(_)}}):null;await q6(Y,V?V.sniEntries():z,G);let L=await Kw(A,j);await d$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS reconcile on start failed: ${_}`,j)}),await v1(L,{rpxDir:Y,verbose:j,ownerPid:I.pid}).catch((_)=>{E("daemon",`DNS setup on start failed: ${_}`,j)}),await kY(A,j).catch(()=>{}),await uY({verbose:j}).catch(()=>{});let N=h8((_)=>{v1(_,{rpxDir:Y,verbose:j,ownerPid:I.pid}).catch((u0)=>{E("daemon",`DNS sync on registry change failed: ${u0}`,j)})},{dir:A,verbose:j}),C=setInterval(()=>{kY(A,j).catch(()=>{}),uY({verbose:j}).catch(()=>{})},W);C.unref?.();let M=null;if(J>0)M=Bun.serve({port:J,hostname:U,fetch(_){return I6(_,V,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,n=60000,r0=30000,Jw=0,n$=Date.now();function g1(){if(T)return;let _={...I.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:j?"1":"0"},u0=Bun.spawn(RR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(d1,pY){if(T)return;let rY=K.indexOf(d1);if(rY!==-1)K.splice(rY,1);let l$=Date.now();if(l$-n$>n)n$=l$,Jw=0;if(Jw++,Jw>D){H.error(`rpx: worker keeps exiting (code ${pY}); giving up after ${D} restarts in ${Math.round(n/1000)}s`);return}let Sw=Math.min(r0,100*2**Math.min(Jw,8));E("daemon",`worker exited (code ${pY}); respawning in ${Sw}ms (restart ${Jw}/${D})`,j),setTimeout(g1,Sw).unref?.()}});K.push(u0)}for(let _=0;_<Q;_++)g1();if(j)H.success(`rpx coordinator listening on https://${U}:${X} via ${Q} worker(s)${M?` (http→https on :${J})`:""}`),H.info(`pid file: ${f}`);let J$,a0=new Promise((_)=>{J$=_});async function Vw(){if(T)return a0;if(T=!0,clearInterval(C),N.close(),M?.stop(!1),F("SIGTERM"),await Promise.race([Promise.all(K.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),F("SIGKILL"),await g$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS teardown failed: ${_}`,j)}),await m1(Y),await i0.unlink(dj(Y)).catch(()=>{}),j)H.info("rpx coordinator stopped");return J$(),a0}let Lw=(_)=>{E("daemon",`coordinator received ${_}, shutting down`,j),Vw().catch(()=>{})};return I.once("SIGINT",Lw),I.once("SIGTERM",Lw),{stop:Vw,done:a0,httpsPort:X,httpPort:J,pidPath:f,ensureCert:(_)=>V?V.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function IR(){let w=I.execPath,$=hw.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&I.argv[1])return[w,I.argv[1],"daemon:start"];return[w,"daemon:start"]}async function g8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await d$({rpxDir:$,verbose:Y}).catch((f)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${f}`,Y)});let A=await V$($);if(A!==null&&Xw(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await m1($);await i0.mkdir($,{recursive:!0});let X=w.spawnCommand??IR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=H6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??I.cwd(),env:w.spawnEnv?{...I.env,...w.spawnEnv}:I.env});J.unref();let U=null;J.once("error",(f)=>{U=f});let j=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,Q=Date.now()+j;while(Date.now()<Q){if(U)throw U;let f=await V$($);if(f!==null&&Xw(f))return E("daemon",`daemon registered with pid=${f}`,Y),{pid:f,spawned:!0};await new Promise((z)=>setTimeout(z,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${j}ms (rpxDir=${$})`)}async function V6(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await V$($);if(U===null||!Xw(U)){if(U!==null)await m1($);return await d$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{I.kill(U,"SIGTERM")}catch(W){let Q=W.code;if(Q==="ESRCH")return await m1($),{stopped:!1,pid:U,forced:!1};if(Q==="EPERM")T$(`kill -TERM ${U}`);else throw W}let j=Date.now()+A;while(Date.now()<j){if(!Xw(U))return E("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);E("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{I.kill(U,"SIGKILL")}catch(W){let Q=W.code;if(Q==="EPERM")T$(`kill -KILL ${U}`);else if(Q!=="ESRCH")throw W}return await m1($),await g$({rpxDir:$,verbose:Y}).catch((W)=>{E("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function L6(w={}){let $=w.rpxDir??V0();if(await m8($))return;await d$({rpxDir:$,verbose:w.verbose})}var FR=5000,c8,T6=!1;var b8=s(()=>{_$();Gj();Fj();Tj();I8();Hj();Rj();QU();n2();M8();q8();v$();Dj();mY();z0();c8=new Map});import{dirname as bR,join as uR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as cR}from"node:url";import{existsSync as t6}from"node:fs";import JJ from"node:fs/promises";import wQ from"node:os";import UJ from"node:path";import S$ from"node:process";import{EventEmitter as a6}from"node:events";import U$ from"node:process";import $Q from"node:process";import fJ from"node:process";import sY from"node:process";import r1 from"node:process";import XQ from"node:tty";import iG,{stdin as UM,stdout as WM}from"node:process";import UQ,{stdin as cG,stdout as vG}from"node:process";import mG from"node:readline";class jQ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=wQ.homedir(),$=UJ.join(w,".config","clapp");this.configPath=UJ.join($,"telemetry.json")}async isEnabled(){if(S$.env.DO_NOT_TRACK==="1"||S$.env.DO_NOT_TRACK==="true")return!1;if(S$.env.NO_TELEMETRY==="1"||S$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:wQ.platform(),nodeVersion:S$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:S$.env.DO_NOT_TRACK==="1"||S$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(t6(this.configPath)){let w=await JJ.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 $=UJ.dirname(this.configPath);await JJ.mkdir($,{recursive:!0}),await JJ.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 rR=new jQ;function s6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let j of Object.keys(A))for(let W of A[j])J[W]=j;for(let j of X)if(A[j])for(let W of A[j])X.add(W);function U(j,W){let Q=J[j]||j;if(Y[Q]=W,A[Q])for(let f of A[Q])Y[f]=W;if(J[j]&&A[J[j]])for(let f of A[J[j]])Y[f]=W;Y[j]=W}for(let j=0;j<w.length;j++){let W=w[j];if(W==="--"){Y._.push(...w.slice(j+1));break}if(W.startsWith("--")){let Q=W.indexOf("=");if(Q!==-1){let f=W.slice(2,Q),z=W.slice(Q+1);U(f,z)}else{let f=W.slice(2);if(f.startsWith("no-")){let B=f.slice(3);U(B,!1);continue}let z=J[f]||f;if(X.has(z)||X.has(f))U(f,!0);else{let B=w[j+1];if(B!==void 0&&!B.startsWith("-"))U(f,B),j++;else U(f,!0)}}}else if(W.startsWith("-")&&W.length>1){let Q=W.slice(1);for(let f=0;f<Q.length;f++){let z=Q[f],B=J[z]||z;if(f===Q.length-1&&!X.has(B)&&!X.has(z)){let G=w[j+1];if(G!==void 0&&!G.startsWith("-"))U(z,G),j++;else U(z,!0)}else U(z,!0)}}else Y._.push(W)}return Y}function QJ(w){return w.replace(/[<[].+/,"").trim()}function o6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(j)=>{let W=!1,Q=j[1];if(Q.startsWith("..."))Q=Q.slice(3),W=!0;return{required:j[0].startsWith("<"),value:Q,variadic:W}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function e6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((j)=>A.names.includes(j))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function YQ(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function WJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function wG(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function $G(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 YG(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 AG(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function QQ(w){return w.split(".").map(($,Y)=>{return Y===0?wG($):$}).join(".")}class aY extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
|
|
298
298
|
|
|
299
299
|
Stack trace:
|
|
300
300
|
${this.stack}`;return this.message}}function XG(){let{env:w}=$Q,{TERM:$,TERM_PROGRAM:Y}=w;if($Q.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",Q0=`${wA}[`;var xw={to(w,$){if(!$)return`${Q0}${w+1}G`;return`${Q0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${Q0}${-w}D`;else if(w>0)Y+=`${Q0}${w}C`;if($<0)Y+=`${Q0}${-$}A`;else if($>0)Y+=`${Q0}${$}B`;return Y},up:(w=1)=>`${Q0}${w}A`,down:(w=1)=>`${Q0}${w}B`,forward:(w=1)=>`${Q0}${w}C`,backward:(w=1)=>`${Q0}${w}D`,nextLine:(w=1)=>`${Q0}E`.repeat(w),prevLine:(w=1)=>`${Q0}F`.repeat(w),left:`${Q0}G`,hide:`${Q0}?25l`,show:`${Q0}?25h`,save:`${wA}7`,restore:`${wA}8`};var jJ={screen:`${Q0}2J`,up:(w=1)=>`${Q0}1J`.repeat(w),down:(w=1)=>`${Q0}J`.repeat(w),line:`${Q0}2K`,lineEnd:`${Q0}K`,lineStart:`${Q0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?xw.up():"");if(w)$+=xw.left;return $}},oR={screen:`${wA}c`};function JG(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 fQ(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:JG(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class zQ{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=QJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return QQ(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 wM=fJ.argv,UG=`${fJ.platform}-${fJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,AQ=sY.argv,WG=`${sY.platform}-${sY.arch} node-${sY.version}`;class zJ{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=QJ(w);let X=QJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=o6(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 zQ(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 BJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let W=YQ($.map((G)=>G.rawName)),Q=new Map,f=[];for(let G of $)if(G.namespace){if(!Q.has(G.namespace))Q.set(G.namespace,[]);Q.get(G.namespace).push(G)}else f.push(G);let z="";if(f.length>0)z+=f.map((G)=>{return` ${WJ(G.rawName,W.length)} ${G.description}`}).join(`
|
|
@@ -323,7 +323,7 @@ Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error du
|
|
|
323
323
|
✗ Command "${w}" not found.
|
|
324
324
|
`)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=fQ(w,$);if(Y.length>0)console.log(p1.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${p1.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(p1.dim("Run"),`${this.name} --help`,p1.dim("to see all available commands")),U$.exit(1)}async parse(w=AQ,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=w,!this.name)this.name=w[1]?AG(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let Q=this.mri(J,W);X=!1;let f={...Q,args:Q.args.slice(1)};this.setParsedInfo(f,W,U),this.emit(`command:${U}`,W);break}}if(X){for(let W of this.commands)if(W.name===""){X=!1;let Q=this.mri(J,W);this.setParsedInfo(Q,W),this.emit("command:!",W);break}}if(X){let W=this.mri(w.slice(2));this.setParsedInfo(W)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let j={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return j}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=e6(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=s6(w,A),j={_:U._};for(let B of Object.keys(U))if(B!=="_")j[QQ(B)]=U[B];let W=j._,Q={"--":X},f=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let B of Y){if(!f&&B.config.default!==void 0)for(let G of B.names)Q[G]=B.config.default;if(Array.isArray(B.config.type)){if(z[B.name]===void 0)z[B.name]={shouldTransform:!0,transformFunction:B.config.type[0]}}}for(let B of Object.keys(j))if(B!=="_"){let G=B.split(".");$G(Q,G,j[B]),YG(Q,z)}return{args:W,options:Q}}async run(w=AQ){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
|
|
325
325
|
Run \`${this.name??"cli"} --help\` for usage.`;U$.stderr.write(`${J}${X}${U}
|
|
326
|
-
`),U$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((j,W)=>{if(j.variadic)A.push(w.slice(W));else A.push(w[W])}),A.push($);let X={command:Y,args:A,options:$};for(let j of Y.beforeHooks)await j(X);let J,U=async()=>{let j=Y.commandAction.apply(this,A);if(j instanceof Promise)J=await j;else J=j;return J};if(Y.middleware.length>0){let j=0,W=async()=>{if(j<Y.middleware.length){let Q=Y.middleware[j++];await Q({...X,next:W})}else await U()};await W()}else await U();for(let j of Y.afterHooks)await j(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return U$.removeAllListeners("SIGINT"),U$.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class BQ{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 YM=new BQ;function zG(){if("FORCE_COLOR"in r1.env)return r1.env.FORCE_COLOR!=="0";if("NO_COLOR"in r1.env||r1.env.TERM==="dumb")return!1;if(r1.platform==="win32")return!0;return XQ.isatty(1)&&XQ.isatty(2)}var GQ=zG();function J0(w,$){if(!GQ)return(Y)=>Y;return(Y)=>w+Y+$}var BG=J0("\x1B[0m","\x1B[0m"),GG=J0("\x1B[31m","\x1B[39m"),EG=J0("\x1B[32m","\x1B[39m"),KG=J0("\x1B[33m","\x1B[39m"),FG=J0("\x1B[34m","\x1B[39m"),TG=J0("\x1B[35m","\x1B[39m"),
|
|
326
|
+
`),U$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((j,W)=>{if(j.variadic)A.push(w.slice(W));else A.push(w[W])}),A.push($);let X={command:Y,args:A,options:$};for(let j of Y.beforeHooks)await j(X);let J,U=async()=>{let j=Y.commandAction.apply(this,A);if(j instanceof Promise)J=await j;else J=j;return J};if(Y.middleware.length>0){let j=0,W=async()=>{if(j<Y.middleware.length){let Q=Y.middleware[j++];await Q({...X,next:W})}else await U()};await W()}else await U();for(let j of Y.afterHooks)await j(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return U$.removeAllListeners("SIGINT"),U$.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class BQ{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 YM=new BQ;function zG(){if("FORCE_COLOR"in r1.env)return r1.env.FORCE_COLOR!=="0";if("NO_COLOR"in r1.env||r1.env.TERM==="dumb")return!1;if(r1.platform==="win32")return!0;return XQ.isatty(1)&&XQ.isatty(2)}var GQ=zG();function J0(w,$){if(!GQ)return(Y)=>Y;return(Y)=>w+Y+$}var BG=J0("\x1B[0m","\x1B[0m"),GG=J0("\x1B[31m","\x1B[39m"),EG=J0("\x1B[32m","\x1B[39m"),KG=J0("\x1B[33m","\x1B[39m"),FG=J0("\x1B[34m","\x1B[39m"),TG=J0("\x1B[35m","\x1B[39m"),qG=J0("\x1B[36m","\x1B[39m"),NG=J0("\x1B[37m","\x1B[39m"),HG=J0("\x1B[90m","\x1B[39m"),RG=J0("\x1B[1m","\x1B[22m"),MG=J0("\x1B[3m","\x1B[23m"),yG=J0("\x1B[4m","\x1B[24m"),IG=J0("\x1B[2m","\x1B[22m"),CG=J0("\x1B[7m","\x1B[27m"),VG=J0("\x1B[8m","\x1B[28m"),LG=J0("\x1B[9m","\x1B[29m"),SG=J0("\x1B[41m","\x1B[49m"),OG=J0("\x1B[42m","\x1B[49m"),hG=J0("\x1B[43m","\x1B[49m"),_G=J0("\x1B[44m","\x1B[49m"),DG=J0("\x1B[45m","\x1B[49m"),xG=J0("\x1B[46m","\x1B[49m"),kG=J0("\x1B[47m","\x1B[49m"),ZG=GQ,PG={reset:BG,red:GG,green:EG,yellow:KG,blue:FG,magenta:TG,cyan:qG,white:NG,gray:HG,bold:RG,italic:MG,underline:yG,dim:IG,inverse:CG,hidden:VG,strikethrough:LG,bgRed:SG,bgGreen:OG,bgYellow:hG,bgBlue:_G,bgMagenta:DG,bgCyan:xG,bgWhite:kG,isColorSupported:ZG},oY=PG,bG=["up","down","left","right","space","enter","cancel"],eY={actions:new Set(bG),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function EQ(w,$){if(typeof w==="string")return eY.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(EQ(Y,$))return!0}return!1}function uG(w,$){if(w===$)return[];let Y=w.split(`
|
|
327
327
|
`),A=$.split(`
|
|
328
328
|
`),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var jM=iG.platform.startsWith("win"),JQ=Symbol("clapp:cancel");function tY(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function gG(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function dG(w){return gG(w).length}function WQ(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
|
|
329
329
|
`),U=[];for(let j of J){if(dG(j)<=$){U.push(X?j.trimEnd():j);continue}if(A){let W="",Q=0,f=0;while(f<j.length){let z=j.slice(f).match(/^\x1b\[[0-9;]*m/);if(z){W+=z[0],f+=z[0].length;continue}if(Q>=$)U.push(X?W.trimEnd():W),W="",Q=0;W+=j[f],Q++,f++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?j.trimEnd():j)}return U.join(`
|
|
@@ -332,7 +332,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;U$.stderr.write(`${J}${X}${U}
|
|
|
332
332
|
`).length-1;this.output.write(xw.move(-999,w*-1))}render(){let w=WQ(this._render(this)??"",UQ.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(xw.hide);else{let $=uG(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(jJ.lines(1));let A=w.split(`
|
|
333
333
|
`);this.output.write(A[Y]),this._prevFrame=w,this.output.write(xw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(jJ.down());let X=w.split(`
|
|
334
334
|
`).slice(Y);this.output.write(X.join(`
|
|
335
|
-
`)),this._prevFrame=w;return}this.output.write(jJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function nG(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 lG(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function pG(w,$){if(!$)return;if(w)return $;return $[0]}class rG extends EJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return oY.inverse(oY.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}${oY.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??lG;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=pG(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=nG(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 tG extends EJ{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 aG=XG();var $0=(w,$)=>aG?w:$,zM=$0("◆","*"),BM=$0("■","x"),GM=$0("▲","x"),EM=$0("◇","o"),KM=$0("┌","T"),sG=$0("│","|"),FM=$0("└","—"),TM=$0("●",">"),
|
|
336
|
-
`,U=(W)=>{let Q=r8(W);return Y.has(Q)||A.some((f)=>wY(Q,f))},j=(W)=>{let Q=hR(W);if(!U(Q))return;let f="/";try{f=new URL(W.url).pathname}catch{}if(X.some((z)=>f.startsWith(z)))return;if(SR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return j.protects=U,j}Fj();Tj();N8();I8();Hj();Rj();M8();z0();var _6={name:"@stacksjs/rpx",type:"module",version:"0.11.41",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var gY=_6.version;var a8=new n8,xR=new L8("0.0.0.0"),nY=new Set,o8=new Set,lj=!1,t8=null,pj=null;async function $J(w){if(lj)return E("cleanup","Cleanup already in progress, skipping",w?.verbose),pj||Promise.resolve();lj=!0,E("cleanup","Starting cleanup process",w?.verbose),pj=new Promise(($)=>{t8=$});try{await a8.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(nY).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),E("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{E("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){E("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),nY.clear();for(let A of o8)P1(A);if(o8.clear(),w?.hosts&&w.domains?.length){E("cleanup","Cleaning up hosts file entries",w?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(w6(A,w?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{E("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){E("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await E2(X,w?.verbose),E("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){E("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),E("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){E("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(t8)t8();t8=null,lj=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(d.env.NODE_ENV!=="test"&&d.env.BUN_ENV!=="test"&&!$)d.exit(0)}return pj}var rj=!1;function Z6(w){if(rj){E("signal",`Received second ${w} signal, forcing exit`,!0),d.exit(1);return}rj=!0,E("signal",`Received ${w} signal, initiating cleanup`,!0),$J().catch(($)=>{E("signal",`Cleanup failed after ${w}: ${$}`,!0),d.exit(1)}).finally(()=>{rj=!1})}d.once("SIGINT",()=>Z6("SIGINT"));d.once("SIGTERM",()=>Z6("SIGTERM"));d.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});d.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function lY(w,$,Y,A=5){E("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(d.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((j,W)=>{let Q=x6.connect({host:w,port:$,timeout:3000});Q.once("connect",()=>{E("connection",`Successfully connected to ${w}:${$}`,Y),Q.end(),j()}),Q.once("timeout",()=>{E("connection",`Connection to ${w}:${$} timed out`,Y),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(f)=>{E("connection",`Failed to connect to ${w}:${$}: ${f}`,Y),Q.destroy(),W(f)})});try{await U()}catch(j){let W=j;if(Date.now()-J>X){E("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return E("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((f)=>setTimeout(f,2000)),lY(w,$,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((f,z)=>{let B=e8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{E("connection",`Received HTTP response with status: ${G.statusCode}`,Y),f()});B.on("error",(G)=>z(G)),B.on("timeout",()=>{B.destroy(),z(Error("HTTP request timed out"))}),B.end()}),E("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(f){return E("connection",`HTTP request to ${w}:${$} failed: ${f}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),lY(w,$,Y,A-1)}let Q=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;E("connection",`${Q}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(Q),H.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function P6(w){E("server",`Starting server with options: ${$$(w)}`,w.verbose);let $=i$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(tj(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await bY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await iY(J,w.verbose)}catch(W){if(H.error("Failed to add hosts entry:",W.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),d.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(j){H.error("Failed to check hosts file:",j.message)}}try{await lY(Y.hostname,X,w.verbose)}catch(j){E("server",`Connection test failed: ${j}`,w.verbose),H.error(j.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=HY({...w,to:A.hostname});if(U=await M$({...w,to:A.hostname,https:w.https}),!U){if(E("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await qY({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await M$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(j){throw E("server",`SSL setup failed: ${j}`,w.verbose),j}E("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await ZR({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function kR(w,$,Y,A,X,J,U,j,W,Q,f,z){E("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${j}`,U);let B=RY(f??A.host,z);yY(B);let G=[{host:$,route:{sourceHost:A.host,upstreamPool:B,cleanUrls:j||!1,changeOrigin:W||!1,basePath:"/",auth:Q}}];if(!s8({routeEntries:G,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw P1(B),Error(`Failed to start proxy server for ${$} on port ${Y}`);o8.add(B),iR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:j,verbose:U})}async function ZR(w){E("setup",`Setting up reverse proxy: ${$$(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:j,vitePluginUsage:W,changeOrigin:Q,cleanUrls:f}=w,z=80,B=443,G=c6(),T=w.portManager||xR,K=tj(w);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await bY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await iY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(L){H.error(`Failed to add ${A} to your hosts file: ${L}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&d.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await bY([A],U))[0]){E("hosts",`${A} not found in hosts file, adding...`,U);try{await iY([A],U)}catch(L){E("hosts",`Failed to add ${A} to hosts file: ${L}`,U)}}}if(J&&!T.usedPorts.has(z)){if(!await y$(z,G,U))E("setup","Starting HTTP redirect server",U),i6(U),T.usedPorts.add(z);else if(E("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let F=J?B:z,N=await y$(F,G,U),R;if(N){if(E("setup",`Port ${F} is already in use`,U),U)H.warn(`Port ${F} is already in use. This may be another instance of rpx or another service.`);if(F===443){if(R=await T.getNextAvailablePort(3443,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(F+1000,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=F,T.usedPorts.add(R),E("setup",`Using standard ${F===443?"HTTPS":"HTTP"} port ${F} for ${A}`,U);await kR($,A,R,X,J,W,U,f,Q,CY(w.auth),Y,w.loadBalancer)}catch(F){E("setup",`Setup failed: ${F}`,U),H.error(`Failed to setup reverse proxy: ${F.message}`),$J({domains:[A],hosts:typeof j==="boolean"?j:j?.hosts,certs:typeof j==="boolean"?j:j?.certs,verbose:U,vitePluginUsage:W})}}function i6(w,$=80,Y=443,A,X){E("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=e8.createServer((U,j)=>{let W=U.url?U.url.split("?",1)[0]:"";if(W.startsWith("/.well-known/acme-challenge/")){if(X){let B=X.challengeStore.handlePath(W);if(B!==void 0){E("redirect",`Serving on-demand ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(A){let B=y8(A,W);if(B!=null){E("redirect",`Serving ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(X){j.writeHead(404,{"content-type":"text/plain"}),j.end("challenge not found");return}}let Q=U.headers.host||"",f=Q.includes(":")?Q.slice(0,Q.indexOf(":")):Q;if(X&&f&&!X.hasCert(f))X.ensureCert(f).catch(()=>{});let z=Y===443?f:`${f}:${Y}`;E("redirect",`Redirecting request from ${Q}${U.url} to https://${z}`,w),j.writeHead(301,{Location:`https://${z}${U.url}`}),j.end()}).listen($);nY.add(J),E("redirect","HTTP redirect server started",w)}function b6(w){let $={...cw,...w};if(E("proxy",`Starting proxy with options: ${$$($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}nj({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((W)=>{H.error(`Failed to register with rpx daemon: ${W.message}`),d.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=d.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (mY(),i8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:$.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else E("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((W)=>{E("dns",`Failed to start DNS server: ${W}`,$.verbose)});let j={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:HY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};E("proxy",`Server options: ${$$(j)}`,$.verbose),P6(j).catch((W)=>{E("proxy",`Failed to start proxy: ${W}`,$.verbose),H.error(`Failed to start proxy: ${W.message}`),$J({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function PR(w){return w?.verbose||!1}function tj(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 u6(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=PR($),A=tj($);if(E("config",`Starting with config: ${$$($,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in $}`,Y),E("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let C="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??$.cleanUrls,changeOrigin:M.changeOrigin??$.changeOrigin,pathRewrites:M.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await nj({proxies:C,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){E("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let q of $.proxies)if(q.start){let C=`${q.from}-${q.to}`;try{E("watch",`Starting command for ${C} with command: ${q.start.command}`,Y),H.info(`Starting command for ${C}...`),await a8.startProcess(C,q.start,Y);let M=i$(q.from),D=new URL(M.startsWith("http")?M:`http://${M}`),n=D.hostname||"localhost",r0=Number(D.port)||80;try{await lY(n,r0,Y),E("watch",`Dev server is ready at ${n}:${r0}`,Y)}catch(Jw){E("watch",`Connection check failed, but continuing with proxy setup: ${Jw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw E("watch",`Failed to start command for ${C}: ${M}`,Y),Error(`Failed to start command for ${C}: ${M}`)}}else E("watch",`No start command for proxy ${q.from} -> ${q.to}`,Y)}else if("start"in $&&$.start){E("watch","Found start command in single proxy config",Y);let q=`${$.from}-${$.to}`;try{if($.start)E("watch",`Starting command: ${$.start.command}`,Y),await a8.startProcess(q,$.start,Y);let C=i$($.from),M=new URL(C.startsWith("http")?C:`http://${C}`),D=M.hostname||"localhost",n=Number(M.port)||80;try{await lY(D,n,Y),E("watch",`Dev server is ready at ${D}:${n}`,Y)}catch(r0){E("watch",`Connection check failed, but continuing with proxy setup: ${r0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw E("watch",`Failed to run start command: ${C}`,Y),Error(`Failed to run start command: ${C}`)}}else E("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(d.platform!=="win32"&&($.https||A)){if(!F$())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),DR("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await DY($.productionCerts,Y),J.length>0)E("ssl",`Using ${J.length} production SNI cert(s): ${J.map((q)=>q.serverName).join(", ")}`,Y)}if($.https){let q=J.length>0?null:await M$($);if(!q&&J.length===0){if(E("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await qY($),q=await M$($),!q)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else E("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=q}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((q)=>({...q,https:$.https,cleanup:$.cleanup,cleanUrls:q.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:q.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],j=U.map((q)=>q.to||"rpx.localhost"),W=J.length>0?J:$._cachedSSLConfig??null,Q=j.filter((q)=>q&&!q.includes("localhost")&&!q.includes("127.0.0.1")),f=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],B=[...new Set(Q.map((q)=>q.split(".").pop()?.toLowerCase()))],G=B.filter((q)=>!!q&&f.includes(q));if(G.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${G.map((q)=>`.${q}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&d.platform==="darwin"&&Q.length>0){let{setupDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),i8));if(await q({domains:Q,verbose:Y})){if(Y)if(B.every((D)=>!!D&&z.includes(D)))H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains`);else H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains (hosts file entries also added)`)}else E("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{E("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),i8));await q({verbose:$.verbose})}catch(q){E("cleanup",`Error stopping DNS server: ${q}`,$.verbose)}try{await a8.stopAll($.verbose)}catch(q){E("cleanup",`Error stopping processes: ${q}`,$.verbose)}await $J({domains:j,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};d.on("SIGINT",T),d.on("SIGTERM",T);let K=$.singlePortMode===!0,F=$.httpsPort??443,N=$.httpPort??80,R=$.originGuard?h6($.originGuard):null,V=!!W&&(U.length>1||K||J.length>0),L=!W&&K&&U.length>0;if(V&&W){E("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${F}`,Y);let q=await D6(U,A,Y),C=null,M=$.onDemandTls,D=M?.enabled?new i1({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??k6.join(wJ.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(a0)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>d.kill(d.pid,"SIGTERM"),10).unref();else Jw(a0)}}):null,n=null,r0=!1;async function Jw(a0){if(n=a0,r0)return;r0=!0;try{while(n){let Vw=n;if(n=null,E("proxies",`rebuilding :${F} with ${Vw.length} SNI cert(s)`,Y),C)nY.delete(C),C.stop(!1);let Lw=!1;for(let _=0;!Lw&&_<60;_++){let u0=s8({routeEntries:q,listenPort:F,sslConfig:Vw,originGuard:R,verbose:Y});if(u0){C=u0,Lw=!0;break}await new Promise((d1)=>setTimeout(d1,Math.min(25*2**Math.min(_,4),500)))}if(!Lw)H.error(`rpx: CRITICAL — could not rebind :${F} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{r0=!1}}if(!await y$(N,"0.0.0.0",Y))i6(Y,N,F,$.acmeChallengeWebroot,D);if(await y$(F,"0.0.0.0",Y)){if(E("proxies",`Port ${F} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${F} is in use. Shared HTTPS proxy cannot start.`);return}let J$=D&&D.sniEntries().length>0?D.sniEntries():W;if(C=s8({routeEntries:q,listenPort:F,sslConfig:J$,originGuard:R,verbose:Y}),!C){H.error(`Shared HTTPS proxy failed to bind :${F}; not exiting`);return}}else if(L){E("proxies",`Creating shared HTTP server for ${U.length} domains on port ${N}`,Y);let q=await D6(U,A,Y);if(await y$(N,"0.0.0.0",Y)){if(E("proxies",`Port ${N} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${N} is in use. Shared HTTP proxy cannot start.`);return}if(!s8({routeEntries:q,listenPort:N,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${N}; not exiting`);return}}else for(let q of U)try{let C=q.to||"rpx.localhost";E("proxy",`Starting proxy for ${C} with SSL config: ${!!W}`,q.verbose),await P6({from:q.from||"localhost:5173",to:C,cleanUrls:q.cleanUrls||!1,https:q.https||!1,cleanup:q.cleanup||!1,vitePluginUsage:q.vitePluginUsage||!1,verbose:q.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:q.changeOrigin||!1,loadBalancer:q.loadBalancer,auth:q.auth,path:q.path,pathRewrites:q.pathRewrites})}catch(C){E("proxies",`Failed to start proxy for ${q.to}: ${C}`,q.verbose),H.error(`Failed to start proxy for ${q.to}:`,C)}}async function D6(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",j=J.cleanUrls||!1,W=J.path,Q=Y$(W),f=CY(J.auth);if(J.redirect){let z=h2(J.redirect);A.push({host:U,path:W,route:{redirect:z,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → redirect ${z.status} ${z.to}${f?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:R8(J.static,j),cleanUrls:j,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${f?" (auth)":""}`,Y);else{let z=i$(J.from),B=new URL(z.startsWith("http")?z:`http://${z}`),G=RY(J.from??B.host,J.loadBalancer);yY(G),o8.add(G),A.push({host:U,path:W,route:{sourceHost:B.host,upstreamPool:G,cleanUrls:j,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → ${B.host}${f?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!U1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await bY([U],Y))[0])await iY([U],Y)}catch{E("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}var dY=null;function c6(){if(d.env.RPX_BIND_HOSTNAME)return d.env.RPX_BIND_HOSTNAME;if(dY)return dY;try{dY=Object.values(wJ.networkInterfaces()).flat().some((Y)=>Y&&Y.family==="IPv6")?"::":"0.0.0.0"}catch{dY="0.0.0.0"}return dY}function s8(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=OY($),j=LY((f,z)=>hY(U,f,z),J),W=X?(f,z)=>X(f)??j(f,z):j,Q=SY(J);try{let f=Bun.serve({port:Y,hostname:c6(),reusePort:TY(),...A?{tls:u$(Array.isArray(A)?A.map((z)=>({serverName:z.serverName,key:z.key,cert:z.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(z,B){return W(z,B)},websocket:Q,error(z){return E("server",`Shared proxy server error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});return nY.add(f),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),f}catch(f){return E("proxies",`Failed to start shared proxy: ${f}`,J),console.error("Failed to start shared proxy:",f),null}}function iR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${_w.green(_w.bold("rpx"))} ${_w.green(`v${gY}`)}`),console.log(` ${_w.green("➜")} ${_w.dim(w?.from??"")} ${_w.dim("➜")} ${_w.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${_w.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${_w.green("➜")} Clean URLs enabled`)}z0();P0.chdir(uR(bR(cR(import.meta.url)),".."));var b0=new GJ("rpx");b0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return u6(cw);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return b6($)});b0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=G8(cw)?cw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):cw.to===w?cw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await l8.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});b0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await l8.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});b0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await l8.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function v6(w){let Y={...(await vf().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}b0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await v6(w.roots):void 0;await(await C6({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});b0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await V6({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});b0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(w)=>{let $=w.rpxDir??V0(),Y=await V$($),A=await m8($),X=w.registryDir,J=await Kw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:L$($),rpxDir:$,registryDir:X??Aw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${L$($)} → pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${L$($)}`);if(console.log(`registry: ${X??Aw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let j=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} → ${U.from} (id=${U.id}${j})`)}});b0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!I$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await b1({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} → ${w.from} (daemon spawn skipped)`);return}try{let $=await g8({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} → ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});b0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(w,$)=>{if(!I$(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await Vj(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await c$(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});b0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(w)=>{let $=w.rpxDir??V0();if(await m8($)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await L6({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});b0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await v6(w.roots),Y=pf($),A=await Kw(w.registryDir).catch(()=>[]),X=new Set(A.map((j)=>j.to)),J=Y.map((j)=>({host:j.host,dir:j.dir,command:j.command,source:j.source,live:X.has(j.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) — scanned ${U.join(", ")}:`);for(let j of J)console.log(` ${j.live?"●":"○"} https://${j.host} ${j.live?"(live)":"(idle)"}`),console.log(` ${j.command} ${j.dir}`)});b0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("node:fs/promises"),{join:A}=await import("node:path"),X=$.rpxDir??V0(),J=A(X,"sites",`${uA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) — looked in ${J}`);return}let j=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,W=U.split(`
|
|
335
|
+
`)),this._prevFrame=w;return}this.output.write(jJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function nG(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 lG(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function pG(w,$){if(!$)return;if(w)return $;return $[0]}class rG extends EJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return oY.inverse(oY.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}${oY.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??lG;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=pG(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=nG(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 tG extends EJ{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 aG=XG();var $0=(w,$)=>aG?w:$,zM=$0("◆","*"),BM=$0("■","x"),GM=$0("▲","x"),EM=$0("◇","o"),KM=$0("┌","T"),sG=$0("│","|"),FM=$0("└","—"),TM=$0("●",">"),qM=$0("○"," "),NM=$0("◻","[•]"),HM=$0("◼","[+]"),RM=$0("◻","[ ]"),MM=$0("▪","•"),yM=$0("─","-"),IM=$0("╮","+"),CM=$0("├","+"),VM=$0("╯","+"),LM=$0("●","•"),SM=$0("◆","*"),OM=$0("▲","!"),hM=$0("■","x");var _M={light:$0("─","-"),heavy:$0("━","="),block:$0("█","#")};function oG(){return`${oY.gray(sG)} `}var DM=oG();bA();QU();b8();_$();z0();import{spawn as CR}from"node:child_process";import*as d8 from"node:process";class n8{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){E("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||d8.cwd();E("start",`Starting process ${w}:`,Y),E("start",` Command: ${A} ${X.join(" ")}`,Y),E("start",` Working directory: ${J}`,Y),E("start",` Environment variables: ${$$($.env)}`,Y);let U=CR(A,X,{cwd:J,env:{...d8.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((j,W)=>{if(U.on("error",(Q)=>{if(!this.isShuttingDown)E("start",`Process ${w} failed to start: ${Q}`,Y),this.processes.delete(w),W(Q)}),U.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)E("start",`Process ${w} exited with code ${Q}; leaving the proxy running`,Y),this.processes.delete(w),W(Error(`Process ${w} exited with code ${Q}`))}),Y)U.stdout?.on("data",(Q)=>{E("process",`[${w}] ${Q.toString().trim()}`,!0)}),U.stderr?.on("data",(Q)=>{E("process",`[${w}] ERR: ${Q.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),W(Error(`Process ${w} was killed during startup`));else E("start",`Process ${w} started successfully`,Y),j()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){E("start",`No process found for ${w}`,$);return}return E("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),E("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){E("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,E("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var l8=new n8;v$();_$();import{execSync as DR}from"node:child_process";import*as e8 from"node:http";import*as x6 from"node:net";import*as wJ from"node:os";import*as k6 from"node:path";import*as d from"node:process";var p8=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,_w={bold:p8(1,22),dim:p8(2,22),green:p8(32,39),cyan:p8(36,39)};bA();b8();_$();v$();z0();import*as S6 from"node:fs";import*as O6 from"node:path";import*as Dw from"node:process";function VR(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function nj(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((B)=>{let G=B.id??VR(B.to,B.path);if(!I$(G))throw Error(`invalid registry id "${G}" derived from to="${B.to}"`);if(A.has(G))throw Error(`duplicate registry id "${G}" — set an explicit \`id\` on one of the proxies`);return A.add(G),{...B,id:G}}),J=new Date().toISOString();for(let B of X)await b1({id:B.id,from:B.from,to:B.to,path:B.path,pid:w.persistent?void 0:Dw.pid,cwd:Dw.cwd(),createdAt:J,cleanUrls:B.cleanUrls,changeOrigin:B.changeOrigin,pathRewrites:B.pathRewrites,static:B.static,loadBalancer:B.loadBalancer},Y,$);let U=await g8({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let B of X){let G=B.static?`static ${typeof B.static==="string"?B.static:B.static.dir}`:B.from;H.success(`https://${B.to} → ${G}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let j=!1,W=Y??Aw(),Q=X.map((B)=>B.id),f=async()=>{if(j)return;j=!0;for(let B of Q)await c$(B,Y,$).catch((G)=>{E("runner",`removeEntry(${B}) failed: ${G}`,$)})},z=(B)=>{E("runner",`received ${B}, unregistering ${Q.length} entries`,$),f().finally(()=>Dw.exit(0))};Dw.once("SIGINT",z),Dw.once("SIGTERM",z),Dw.once("exit",()=>{if(j)return;for(let B of Q)try{S6.unlinkSync(O6.join(W,`${B}.json`))}catch{}}),await new Promise(()=>{})}Dj();Gj();yj();import{timingSafeEqual as LR}from"node:crypto";function SR(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return LR(Y,A)}function r8(w){return w.toLowerCase().replace(/\.$/,"")}var OR=["/.well-known/acme-challenge/"];function hR(w){let $=w.headers.get("host");if($)return r8($.split(":")[0]);try{return r8(new URL(w.url).hostname)}catch{return""}}function h6(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let W of w.hosts){let Q=r8(W);if(Q.startsWith("*."))A.push(Q);else Y.add(Q)}let X=w.exemptPaths??OR,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
336
|
+
`,U=(W)=>{let Q=r8(W);return Y.has(Q)||A.some((f)=>wY(Q,f))},j=(W)=>{let Q=hR(W);if(!U(Q))return;let f="/";try{f=new URL(W.url).pathname}catch{}if(X.some((z)=>f.startsWith(z)))return;if(SR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return j.protects=U,j}Fj();Tj();q8();I8();Hj();Rj();M8();z0();var _6={name:"@stacksjs/rpx",type:"module",version:"0.11.42",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var gY=_6.version;var a8=new n8,xR=new L8("0.0.0.0"),nY=new Set,o8=new Set,lj=!1,t8=null,pj=null;async function $J(w){if(lj)return E("cleanup","Cleanup already in progress, skipping",w?.verbose),pj||Promise.resolve();lj=!0,E("cleanup","Starting cleanup process",w?.verbose),pj=new Promise(($)=>{t8=$});try{await a8.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(nY).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),E("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{E("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){E("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),nY.clear();for(let A of o8)P1(A);if(o8.clear(),w?.hosts&&w.domains?.length){E("cleanup","Cleaning up hosts file entries",w?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(w6(A,w?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{E("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){E("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await E2(X,w?.verbose),E("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){E("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),E("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){E("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(t8)t8();t8=null,lj=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(d.env.NODE_ENV!=="test"&&d.env.BUN_ENV!=="test"&&!$)d.exit(0)}return pj}var rj=!1;function Z6(w){if(rj){E("signal",`Received second ${w} signal, forcing exit`,!0),d.exit(1);return}rj=!0,E("signal",`Received ${w} signal, initiating cleanup`,!0),$J().catch(($)=>{E("signal",`Cleanup failed after ${w}: ${$}`,!0),d.exit(1)}).finally(()=>{rj=!1})}d.once("SIGINT",()=>Z6("SIGINT"));d.once("SIGTERM",()=>Z6("SIGTERM"));d.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});d.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function lY(w,$,Y,A=5){E("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(d.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((j,W)=>{let Q=x6.connect({host:w,port:$,timeout:3000});Q.once("connect",()=>{E("connection",`Successfully connected to ${w}:${$}`,Y),Q.end(),j()}),Q.once("timeout",()=>{E("connection",`Connection to ${w}:${$} timed out`,Y),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(f)=>{E("connection",`Failed to connect to ${w}:${$}: ${f}`,Y),Q.destroy(),W(f)})});try{await U()}catch(j){let W=j;if(Date.now()-J>X){E("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return E("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((f)=>setTimeout(f,2000)),lY(w,$,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((f,z)=>{let B=e8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{E("connection",`Received HTTP response with status: ${G.statusCode}`,Y),f()});B.on("error",(G)=>z(G)),B.on("timeout",()=>{B.destroy(),z(Error("HTTP request timed out"))}),B.end()}),E("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(f){return E("connection",`HTTP request to ${w}:${$} failed: ${f}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),lY(w,$,Y,A-1)}let Q=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;E("connection",`${Q}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(Q),H.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function P6(w){E("server",`Starting server with options: ${$$(w)}`,w.verbose);let $=i$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(tj(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await bY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await iY(J,w.verbose)}catch(W){if(H.error("Failed to add hosts entry:",W.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),d.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(j){H.error("Failed to check hosts file:",j.message)}}try{await lY(Y.hostname,X,w.verbose)}catch(j){E("server",`Connection test failed: ${j}`,w.verbose),H.error(j.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=HY({...w,to:A.hostname});if(U=await M$({...w,to:A.hostname,https:w.https}),!U){if(E("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await NY({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await M$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(j){throw E("server",`SSL setup failed: ${j}`,w.verbose),j}E("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await ZR({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function kR(w,$,Y,A,X,J,U,j,W,Q,f,z){E("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${j}`,U);let B=RY(f??A.host,z);yY(B);let G=[{host:$,route:{sourceHost:A.host,upstreamPool:B,cleanUrls:j||!1,changeOrigin:W||!1,basePath:"/",auth:Q}}];if(!s8({routeEntries:G,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw P1(B),Error(`Failed to start proxy server for ${$} on port ${Y}`);o8.add(B),iR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:j,verbose:U})}async function ZR(w){E("setup",`Setting up reverse proxy: ${$$(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:j,vitePluginUsage:W,changeOrigin:Q,cleanUrls:f}=w,z=80,B=443,G=c6(),T=w.portManager||xR,K=tj(w);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await bY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await iY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(L){H.error(`Failed to add ${A} to your hosts file: ${L}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&d.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await bY([A],U))[0]){E("hosts",`${A} not found in hosts file, adding...`,U);try{await iY([A],U)}catch(L){E("hosts",`Failed to add ${A} to hosts file: ${L}`,U)}}}if(J&&!T.usedPorts.has(z)){if(!await y$(z,G,U))E("setup","Starting HTTP redirect server",U),i6(U),T.usedPorts.add(z);else if(E("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let F=J?B:z,q=await y$(F,G,U),R;if(q){if(E("setup",`Port ${F} is already in use`,U),U)H.warn(`Port ${F} is already in use. This may be another instance of rpx or another service.`);if(F===443){if(R=await T.getNextAvailablePort(3443,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(F+1000,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=F,T.usedPorts.add(R),E("setup",`Using standard ${F===443?"HTTPS":"HTTP"} port ${F} for ${A}`,U);await kR($,A,R,X,J,W,U,f,Q,CY(w.auth),Y,w.loadBalancer)}catch(F){E("setup",`Setup failed: ${F}`,U),H.error(`Failed to setup reverse proxy: ${F.message}`),$J({domains:[A],hosts:typeof j==="boolean"?j:j?.hosts,certs:typeof j==="boolean"?j:j?.certs,verbose:U,vitePluginUsage:W})}}function i6(w,$=80,Y=443,A,X){E("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=e8.createServer((U,j)=>{let W=U.url?U.url.split("?",1)[0]:"";if(W.startsWith("/.well-known/acme-challenge/")){if(X){let B=X.challengeStore.handlePath(W);if(B!==void 0){E("redirect",`Serving on-demand ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(A){let B=y8(A,W);if(B!=null){E("redirect",`Serving ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(X){j.writeHead(404,{"content-type":"text/plain"}),j.end("challenge not found");return}}let Q=U.headers.host||"",f=Q.includes(":")?Q.slice(0,Q.indexOf(":")):Q;if(X&&f&&!X.hasCert(f))X.ensureCert(f).catch(()=>{});let z=Y===443?f:`${f}:${Y}`;E("redirect",`Redirecting request from ${Q}${U.url} to https://${z}`,w),j.writeHead(301,{Location:`https://${z}${U.url}`}),j.end()}).listen($);nY.add(J),E("redirect","HTTP redirect server started",w)}function b6(w){let $={...cw,...w};if(E("proxy",`Starting proxy with options: ${$$($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}nj({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((W)=>{H.error(`Failed to register with rpx daemon: ${W.message}`),d.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=d.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (mY(),i8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:$.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else E("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((W)=>{E("dns",`Failed to start DNS server: ${W}`,$.verbose)});let j={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:HY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};E("proxy",`Server options: ${$$(j)}`,$.verbose),P6(j).catch((W)=>{E("proxy",`Failed to start proxy: ${W}`,$.verbose),H.error(`Failed to start proxy: ${W.message}`),$J({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function PR(w){return w?.verbose||!1}function tj(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 u6(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=PR($),A=tj($);if(E("config",`Starting with config: ${$$($,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in $}`,Y),E("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let C="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??$.cleanUrls,changeOrigin:M.changeOrigin??$.changeOrigin,pathRewrites:M.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await nj({proxies:C,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){E("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let N of $.proxies)if(N.start){let C=`${N.from}-${N.to}`;try{E("watch",`Starting command for ${C} with command: ${N.start.command}`,Y),H.info(`Starting command for ${C}...`),await a8.startProcess(C,N.start,Y);let M=i$(N.from),D=new URL(M.startsWith("http")?M:`http://${M}`),n=D.hostname||"localhost",r0=Number(D.port)||80;try{await lY(n,r0,Y),E("watch",`Dev server is ready at ${n}:${r0}`,Y)}catch(Jw){E("watch",`Connection check failed, but continuing with proxy setup: ${Jw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw E("watch",`Failed to start command for ${C}: ${M}`,Y),Error(`Failed to start command for ${C}: ${M}`)}}else E("watch",`No start command for proxy ${N.from} -> ${N.to}`,Y)}else if("start"in $&&$.start){E("watch","Found start command in single proxy config",Y);let N=`${$.from}-${$.to}`;try{if($.start)E("watch",`Starting command: ${$.start.command}`,Y),await a8.startProcess(N,$.start,Y);let C=i$($.from),M=new URL(C.startsWith("http")?C:`http://${C}`),D=M.hostname||"localhost",n=Number(M.port)||80;try{await lY(D,n,Y),E("watch",`Dev server is ready at ${D}:${n}`,Y)}catch(r0){E("watch",`Connection check failed, but continuing with proxy setup: ${r0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw E("watch",`Failed to run start command: ${C}`,Y),Error(`Failed to run start command: ${C}`)}}else E("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(d.platform!=="win32"&&($.https||A)){if(!F$())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),DR("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await DY($.productionCerts,Y),J.length>0)E("ssl",`Using ${J.length} production SNI cert(s): ${J.map((N)=>N.serverName).join(", ")}`,Y)}if($.https){let N=J.length>0?null:await M$($);if(!N&&J.length===0){if(E("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await NY($),N=await M$($),!N)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else E("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=N}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((N)=>({...N,https:$.https,cleanup:$.cleanup,cleanUrls:N.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:N.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],j=U.map((N)=>N.to||"rpx.localhost"),W=J.length>0?J:$._cachedSSLConfig??null,Q=j.filter((N)=>N&&!N.includes("localhost")&&!N.includes("127.0.0.1")),f=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],B=[...new Set(Q.map((N)=>N.split(".").pop()?.toLowerCase()))],G=B.filter((N)=>!!N&&f.includes(N));if(G.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${G.map((N)=>`.${N}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&d.platform==="darwin"&&Q.length>0){let{setupDevelopmentDns:N}=await Promise.resolve().then(() => (mY(),i8));if(await N({domains:Q,verbose:Y})){if(Y)if(B.every((D)=>!!D&&z.includes(D)))H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains`);else H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains (hosts file entries also added)`)}else E("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{E("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:N}=await Promise.resolve().then(() => (mY(),i8));await N({verbose:$.verbose})}catch(N){E("cleanup",`Error stopping DNS server: ${N}`,$.verbose)}try{await a8.stopAll($.verbose)}catch(N){E("cleanup",`Error stopping processes: ${N}`,$.verbose)}await $J({domains:j,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};d.on("SIGINT",T),d.on("SIGTERM",T);let K=$.singlePortMode===!0,F=$.httpsPort??443,q=$.httpPort??80,R=$.originGuard?h6($.originGuard):null,V=!!W&&(U.length>1||K||J.length>0),L=!W&&K&&U.length>0;if(V&&W){E("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${F}`,Y);let N=await D6(U,A,Y),C=null,M=$.onDemandTls,D=M?.enabled?new i1({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??k6.join(wJ.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(a0)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>d.kill(d.pid,"SIGTERM"),10).unref();else Jw(a0)}}):null,n=null,r0=!1;async function Jw(a0){if(n=a0,r0)return;r0=!0;try{while(n){let Vw=n;if(n=null,E("proxies",`rebuilding :${F} with ${Vw.length} SNI cert(s)`,Y),C)nY.delete(C),C.stop(!1);let Lw=!1;for(let _=0;!Lw&&_<60;_++){let u0=s8({routeEntries:N,listenPort:F,sslConfig:Vw,originGuard:R,verbose:Y});if(u0){C=u0,Lw=!0;break}await new Promise((d1)=>setTimeout(d1,Math.min(25*2**Math.min(_,4),500)))}if(!Lw)H.error(`rpx: CRITICAL — could not rebind :${F} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{r0=!1}}if(!await y$(q,"0.0.0.0",Y))i6(Y,q,F,$.acmeChallengeWebroot,D);if(await y$(F,"0.0.0.0",Y)){if(E("proxies",`Port ${F} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${F} is in use. Shared HTTPS proxy cannot start.`);return}let J$=D&&D.sniEntries().length>0?D.sniEntries():W;if(C=s8({routeEntries:N,listenPort:F,sslConfig:J$,originGuard:R,verbose:Y}),!C){H.error(`Shared HTTPS proxy failed to bind :${F}; not exiting`);return}}else if(L){E("proxies",`Creating shared HTTP server for ${U.length} domains on port ${q}`,Y);let N=await D6(U,A,Y);if(await y$(q,"0.0.0.0",Y)){if(E("proxies",`Port ${q} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${q} is in use. Shared HTTP proxy cannot start.`);return}if(!s8({routeEntries:N,listenPort:q,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${q}; not exiting`);return}}else for(let N of U)try{let C=N.to||"rpx.localhost";E("proxy",`Starting proxy for ${C} with SSL config: ${!!W}`,N.verbose),await P6({from:N.from||"localhost:5173",to:C,cleanUrls:N.cleanUrls||!1,https:N.https||!1,cleanup:N.cleanup||!1,vitePluginUsage:N.vitePluginUsage||!1,verbose:N.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:N.changeOrigin||!1,loadBalancer:N.loadBalancer,auth:N.auth,path:N.path,pathRewrites:N.pathRewrites})}catch(C){E("proxies",`Failed to start proxy for ${N.to}: ${C}`,N.verbose),H.error(`Failed to start proxy for ${N.to}:`,C)}}async function D6(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",j=J.cleanUrls||!1,W=J.path,Q=Y$(W),f=CY(J.auth);if(J.redirect){let z=h2(J.redirect);A.push({host:U,path:W,route:{redirect:z,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → redirect ${z.status} ${z.to}${f?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:R8(J.static,j),cleanUrls:j,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${f?" (auth)":""}`,Y);else{let z=i$(J.from),B=new URL(z.startsWith("http")?z:`http://${z}`),G=RY(J.from??B.host,J.loadBalancer);yY(G),o8.add(G),A.push({host:U,path:W,route:{sourceHost:B.host,upstreamPool:G,cleanUrls:j,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → ${B.host}${f?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!U1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await bY([U],Y))[0])await iY([U],Y)}catch{E("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}var dY=null;function c6(){if(d.env.RPX_BIND_HOSTNAME)return d.env.RPX_BIND_HOSTNAME;if(dY)return dY;try{dY=Object.values(wJ.networkInterfaces()).flat().some((Y)=>Y&&Y.family==="IPv6")?"::":"0.0.0.0"}catch{dY="0.0.0.0"}return dY}function s8(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=OY($),j=LY((f,z)=>hY(U,f,z),J),W=X?(f,z)=>X(f)??j(f,z):j,Q=SY(J);try{let f=Bun.serve({port:Y,hostname:c6(),reusePort:TY(),...A?{tls:u$(Array.isArray(A)?A.map((z)=>({serverName:z.serverName,key:z.key,cert:z.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(z,B){return W(z,B)},websocket:Q,error(z){return E("server",`Shared proxy server error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});return nY.add(f),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),f}catch(f){return E("proxies",`Failed to start shared proxy: ${f}`,J),console.error("Failed to start shared proxy:",f),null}}function iR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${_w.green(_w.bold("rpx"))} ${_w.green(`v${gY}`)}`),console.log(` ${_w.green("➜")} ${_w.dim(w?.from??"")} ${_w.dim("➜")} ${_w.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${_w.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${_w.green("➜")} Clean URLs enabled`)}z0();P0.chdir(uR(bR(cR(import.meta.url)),".."));var b0=new GJ("rpx");b0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return u6(cw);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return b6($)});b0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=G8(cw)?cw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):cw.to===w?cw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await l8.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});b0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await l8.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});b0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await l8.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function v6(w){let Y={...(await vf().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}b0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await v6(w.roots):void 0;await(await C6({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});b0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await V6({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});b0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(w)=>{let $=w.rpxDir??V0(),Y=await V$($),A=await m8($),X=w.registryDir,J=await Kw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:L$($),rpxDir:$,registryDir:X??Aw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${L$($)} → pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${L$($)}`);if(console.log(`registry: ${X??Aw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let j=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} → ${U.from} (id=${U.id}${j})`)}});b0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!I$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await b1({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} → ${w.from} (daemon spawn skipped)`);return}try{let $=await g8({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} → ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});b0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(w,$)=>{if(!I$(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await Vj(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await c$(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});b0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(w)=>{let $=w.rpxDir??V0();if(await m8($)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await L6({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});b0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await v6(w.roots),Y=pf($),A=await Kw(w.registryDir).catch(()=>[]),X=new Set(A.map((j)=>j.to)),J=Y.map((j)=>({host:j.host,dir:j.dir,command:j.command,source:j.source,live:X.has(j.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) — scanned ${U.join(", ")}:`);for(let j of J)console.log(` ${j.live?"●":"○"} https://${j.host} ${j.live?"(live)":"(idle)"}`),console.log(` ${j.command} ${j.dir}`)});b0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("node:fs/promises"),{join:A}=await import("node:path"),X=$.rpxDir??V0(),J=A(X,"sites",`${uA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) — looked in ${J}`);return}let j=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,W=U.split(`
|
|
337
337
|
`);P0.stdout.write((j&&j>0?W.slice(-j):W).join(`
|
|
338
338
|
`))});b0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(gY)});b0.version(gY);b0.help();b0.run();
|