@stacksjs/rpx 0.11.45 → 0.11.46
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 +231 -239
- package/dist/chunk-086aa2f7.js +1 -0
- package/dist/chunk-nnnptjfw.js +49 -0
- package/dist/chunk-t3s94va5.js +1 -0
- package/dist/chunk-z0swphpg.js +253 -0
- package/dist/index.js +2 -2
- package/dist/proxy-handler.d.ts +2 -1
- package/dist/proxy-pool.d.ts +1 -0
- package/package.json +1 -1
- package/dist/chunk-bvq3wmhm.js +0 -1
- package/dist/chunk-t6pzd7ec.js +0 -252
- package/dist/chunk-vce43wgr.js +0 -1
- package/dist/chunk-w4t1nar9.js +0 -49
package/dist/bin/cli.js
CHANGED
|
@@ -1,256 +1,257 @@
|
|
|
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 FQ,statSync as EQ}from"fs";import{existsSync as eG,mkdirSync as mM,readdirSync as gM,readFileSync as w5,writeFileSync as dM}from"fs";import{homedir as r$}from"os";import{dirname as pM,resolve as jw}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 t$}from"os";import{dirname as qQ,resolve as g0}from"path";import S$ from"process";import{join as X5,relative as J5,resolve as HQ}from"path";import RA from"process";import{existsSync as Az,mkdirSync as A4,readdirSync as X4,writeFileSync as J4}from"fs";import{homedir as FJ}from"os";import{dirname as j4,resolve as m0}from"path";import s1 from"process";import{join as U5,relative as W5,resolve as RQ}from"path";import MA from"process";import{existsSync as Xz,mkdirSync as G4,readdirSync as K4,writeFileSync as F4}from"fs";import{dirname as T4,resolve as IA}from"path";import PJ from"process";import{Buffer as j$}from"buffer";import{createCipheriv as j5,createDecipheriv as Q5,randomBytes as EJ}from"crypto";import{closeSync as TJ,createReadStream as MQ,createWriteStream as z5,existsSync as NJ,fsyncSync as IQ,openSync as yQ,writeFileSync as f5}from"fs";import{access as B5,constants as CQ,mkdir as G5,readdir as $A,rename as VQ,stat as a$,unlink as YA,writeFile as qJ}from"fs/promises";import{join as s$}from"path";import L0 from"process";import{pipeline as K5}from"stream/promises";import{createGzip as LQ}from"zlib";import o$ from"process";import Pw from"process";import{Buffer as kw}from"buffer";import{createCipheriv as F5,createDecipheriv as E5,randomBytes as HJ}from"crypto";import{closeSync as RJ,createReadStream as OQ,createWriteStream as T5,existsSync as AA,fsyncSync as SQ,openSync as _Q,writeFileSync as N5}from"fs";import{access as q5,constants as hQ,mkdir as H5,readdir as XA,rename as DQ,stat as e$,unlink as JA,writeFile as MJ}from"fs/promises";import{isAbsolute as R5,join as w1,resolve as M5}from"path";import x from"process";import{pipeline as I5}from"stream/promises";import{createGzip as xQ}from"zlib";import $1 from"process";import iw from"process";import UA from"process";import{existsSync as WA}from"fs";import{resolve as IJ}from"path";import{existsSync as y5}from"fs";import{existsSync as C5,readdirSync as V5}from"fs";import{extname as yJ,resolve as kQ}from"path";import L5 from"process";import{join as O5,relative as S5,resolve as ZQ}from"path";import yA from"process";import{Buffer as Zw}from"buffer";import{createCipheriv as _5,createDecipheriv as h5,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 vQ,stat as Y1,unlink as zA,writeFile as LJ}from"fs/promises";import{isAbsolute as P5,join as A1,resolve as i5}from"path";import k from"process";import{pipeline as b5}from"stream/promises";import{createGzip as cQ}from"zlib";import X1 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 XF}from"fs";class $z{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(!FQ(w))return!0;return EQ(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=FQ(Y)?EQ(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 Yz{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 c5(w,$){this[w]=v5.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(!Xz(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=IA(A,`${U}${j}`),Q=await p5(W,Y);if(Q!==null)return Q}try{let U=IA(A,"package.json");if(Xz(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:EA,cwd:MA.cwd(),endpoint:"",headers:{}});return{...EA,...w}}catch{return EA}}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 Uz{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:o$.pid,hostname:$(),environment:o$.env.NODE_ENV||"development",platform:o$.platform,version:o$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:o$.env.NODE_ENV||o$.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 Uz,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=yQ(this.currentLogFile,"a",420),f5(X,W,{flag:"a"}),IQ(X),X!==void 0)TJ(X),X=void 0;if((await a$(this.currentLogFile)).size===0){if(await qJ(this.currentLogFile,W,{flag:"w",mode:420}),(await a$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{TJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,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 s$(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 s$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return s$(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 EJ(16).toString("hex")}generateKey(){return EJ(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=EJ(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 a$(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 z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await a$(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 a$(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(s$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=MQ(w),A=z5($),X=LQ();await K5(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=yQ(this.currentLogFile,"r+");IQ(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(s$(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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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=Ez[w],z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:o.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:o.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f),j){let B=j.split(`
|
|
3
|
-
`);for(let
|
|
4
|
-
`;if(
|
|
5
|
-
`;
|
|
6
|
-
`,
|
|
7
|
-
`),
|
|
8
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
9
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
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=s$(this.config.logDirectory,A);if(w.before)try{if((await a$(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 FA(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]=FA(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"?$:FA(w,$);if(Array.isArray(w))return Y==="replace"?$:FA(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]=FA(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 fA(w,$,Y="replace"){if(!Az(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,z]of Object.entries(U)){let f=[...j,Q],B=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(B).join("_")}`,T=`${A}_${f.map((F)=>F.toUpperCase()).join("_")}`;if(Y)S0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[Q]=J(z,f);else{let F=s1.env[G]||s1.env[T];if(F!==void 0){if(Y)S0.info(`Using environment variable ${F?G:T} for config ${w}.${f.join(".")}`);if(typeof z==="number")W[Q]=Number(F);else if(typeof z==="boolean")W[Q]=F.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(F);if(Array.isArray(E))W[Q]=E;else W[Q]=F.split(",").map((N)=>N.trim())}catch{W[Q]=F.split(",").map((E)=>E.trim())}else W[Q]=F}}}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||s1.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)S0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let f=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([Q,m0(Q,"config"),m0(Q,".config"),A?m0(Q,A):void 0].filter(Boolean)));for(let E of F){if(J)S0.info(`Searching for configuration in: ${E}`);let R=[m0(Q,"config"),m0(Q,".config")].concat(A?[m0(Q,A)]:[]).includes(E)?[...f,...B,...G,...T]:[...B,...f,...T,...G];for(let V of R)for(let L of z){let q=m0(E,`${V}${L}`),C=await fA(q,W,j);if(C!==null){if(J)S0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let E=m0(FJ(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)S0.info(`Checking user config directory: ${E}`);for(let R of N)for(let V of z){let L=m0(E,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)S0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let E=m0(FJ(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)S0.info(`Checking user config directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=m0(E,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)S0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let E=FJ(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)S0.info(`Checking user home directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=m0(E,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)S0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let E=m0(Q,"package.json");if(Az(E)){let N=await import(E),R=N[w];if(!R&&$){if(R=N[$],R&&J)S0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)S0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return sJ(W,R,j)}catch(V){if(J)S0.warn("Failed to merge package.json config:",V)}}}catch(E){if(J)S0.warn("Failed to load package.json:",E)}if(J)S0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function wK(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 $K(){try{let w=await e5({name:"clarity",alias:"logging",defaultConfig:NA,cwd:RA.cwd()});return{...NA,...w||{}}}catch{return NA}}function K0(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YK(){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 Wz{async format(w){let $=await YK(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:$1.pid,hostname:$(),environment:$1.env.NODE_ENV||"development",platform:$1.platform,version:$1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$1.env.NODE_ENV||$1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class OA{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 Wz,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!K0()&&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,hQ.F_OK|hQ.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=_Q(this.currentLogFile,"a",420),N5(X,W,{flag:"a"}),SQ(X),X!==void 0)RJ(X),X=void 0;if((await e$(this.currentLogFile)).size===0){if(await MJ(this.currentLogFile,W,{flag:"w",mode:420}),(await e$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{RJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,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 w1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return w1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(K0())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=F5("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(K0())return;if(!this.shouldWriteToFile())return;let w=await e$(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 z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await e$(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 e$(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(w1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=OQ(w),A=T5($),X=xQ();await I5(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=_Q(this.currentLogFile,"r+");SQ(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(!K0()&&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(w1(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||K0())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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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(K0())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 f=this.options.showIcons===!1?"":Tz[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:f,tag:B,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
11
|
-
`);for(let
|
|
12
|
-
`;if(
|
|
13
|
-
`;if(
|
|
14
|
-
`);if(this[
|
|
15
|
-
`,
|
|
16
|
-
`),
|
|
17
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
18
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
19
|
-
`)}finishProgressBar(
|
|
2
|
+
import{createRequire as Kw}from"node:module";var jw=Object.defineProperty;var Uw=(e)=>e;function Ww(e,t){this[e]=Uw.bind(null,t)}var Qf=(e,t)=>{for(var r in t)jw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Ww.bind(t,r)})};var Q=(e,t)=>()=>(e&&(t=e(e=0)),t);var I=Kw(import.meta.url);import{existsSync as fh,statSync as hh}from"fs";import{existsSync as Iv,mkdirSync as AA,readdirSync as kA,readFileSync as _v,writeFileSync as OA}from"fs";import{homedir as Gr}from"os";import{dirname as FA,resolve as lt}from"path";import Ns from"process";import{existsSync as dh,statSync as mh}from"fs";import{existsSync as Nc,mkdirSync as jv,readdirSync as Uv,writeFileSync as Wv}from"fs";import{homedir as qr}from"os";import{dirname as gh,resolve as He}from"path";import Ar from"process";import{join as Kv,relative as Hv,resolve as ph}from"path";import vs from"process";import{existsSync as Zh,mkdirSync as HA,readdirSync as VA,writeFileSync as YA}from"fs";import{homedir as hc}from"os";import{dirname as qA,resolve as Ke}from"path";import Xi from"process";import{join as Vv,relative as Yv,resolve as yh}from"path";import bs from"process";import{existsSync as ed,mkdirSync as e1,readdirSync as t1,writeFileSync as r1}from"fs";import{dirname as n1,resolve as $s}from"path";import Dc from"process";import{Buffer as cr}from"buffer";import{createCipheriv as zv,createDecipheriv as Gv,randomBytes as dc}from"crypto";import{closeSync as mc,createReadStream as wh,createWriteStream as qv,existsSync as gc,fsyncSync as vh,openSync as bh,writeFileSync as Jv}from"fs";import{access as Xv,constants as $h,mkdir as Qv,readdir as Zn,rename as xh,stat as Jr,unlink as es,writeFile as pc}from"fs/promises";import{join as Xr}from"path";import Re from"process";import{pipeline as Zv}from"stream/promises";import{createGzip as Ch}from"zlib";import Qr from"process";import Lt from"process";import{Buffer as Ft}from"buffer";import{createCipheriv as eb,createDecipheriv as tb,randomBytes as yc}from"crypto";import{closeSync as wc,createReadStream as Sh,createWriteStream as rb,existsSync as ts,fsyncSync as Eh,openSync as Th,writeFileSync as ib}from"fs";import{access as nb,constants as Ph,mkdir as sb,readdir as rs,rename as Rh,stat as Zr,unlink as is,writeFile as vc}from"fs/promises";import{isAbsolute as ob,join as ei,resolve as ab}from"path";import F from"process";import{pipeline as cb}from"stream/promises";import{createGzip as Ah}from"zlib";import ti from"process";import Mt from"process";import ns from"process";import{existsSync as ss}from"fs";import{resolve as bc}from"path";import{existsSync as lb}from"fs";import{existsSync as ub,readdirSync as fb}from"fs";import{extname as $c,resolve as kh}from"path";import hb from"process";import{join as db,relative as mb,resolve as Oh}from"path";import xs from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as gb,createDecipheriv as pb,randomBytes as xc}from"crypto";import{closeSync as Cc,createReadStream as Nh,createWriteStream as yb,existsSync as os,fsyncSync as Dh,openSync as Fh,writeFileSync as wb}from"fs";import{access as vb,constants as Bh,mkdir as bb,readdir as as,rename as Lh,stat as ri,unlink as cs,writeFile as Sc}from"fs/promises";import{isAbsolute as $b,join as ii,resolve as xb}from"path";import B from"process";import{pipeline as Cb}from"stream/promises";import{createGzip as Mh}from"zlib";import ni from"process";import It from"process";import us from"process";import{existsSync as fs}from"fs";import{resolve as kc}from"path";import{existsSync as K$}from"fs";class Xh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!fh(e))return!0;return hh(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=fh(r)?hh(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Qh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tb(e,t){this[e]=Eb.bind(null,t)}class Vc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!dh(e))return!0;return mh(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=dh(r)?mh(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Yc{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Ab(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function kb(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Ob(e){return e.getStats().size*2}function zc(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ie(t[0])&&"id"in t[0]&&t[0].id===3&&ie(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ie(t)&&ie(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ie(e)&&"arr"in e&&Array.isArray(e.arr)&&ie(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ie(t[0])&&ie(e[0])){let i=[...t];for(let n of e)if(ie(n)&&"name"in n){if(!i.find((o)=>ie(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(ie(n)&&"path"in n){if(!i.find((o)=>ie(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Cs(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ie(t)||!ie(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ie(n)&&ie(r[i]))r[i]=zc(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ie(n[0])&&ie(r[i][0])){let s=[...n];for(let o of r[i])if(ie(o)&&"name"in o){if(!s.find((a)=>ie(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(ie(o)&&"path"in o){if(!s.find((a)=>ie(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Cs(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Cs(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Cs(e[r],t[r]))return!1;return!0}if(ie(e)&&ie(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Cs(e[n],t[n]))return!1}return!0}return!1}function ie(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Nb(e,t){if(!ed(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return zc(t,i)}catch{return null}}catch{return null}}async function Db({name:e="",cwd:t,defaultConfig:r}){let i=t||Dc.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of n){let a=$s(i,`${o}${c}`),l=await Nb(a,r);if(l!==null)return l}try{let o=$s(i,"package.json");if(ed(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return zc(r,a)}catch{}}}catch{}return r}function Fb(e,t={}){let r=bs.cwd();while(r.includes("storage"))r=yh(r,"..");let i=yh(r,e||"");if(t?.relative)return Yv(bs.cwd(),i);return i}async function Bb(){try{let e=await Db({name:"clarity",defaultConfig:ms,cwd:bs.cwd(),endpoint:"",headers:{}});return{...ms,...e}}catch{return ms}}function ae(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lb(){if(Lt.env.NODE_ENV==="test"||Lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Lt<"u"){let e=Lt.type;if(e==="renderer"||e==="worker")return!1;return!!(Lt.versions&&(Lt.versions.node||Lt.versions.bun))}return!1}class rd{async format(e){let t=await Lb(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qr.pid,hostname:t(),environment:Qr.env.NODE_ENV||"development",platform:Qr.platform,version:Qr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qr.env.NODE_ENV||Qr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ss{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(e,t={}){this.name=e,this.config={...Bc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new rd,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Re.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...gs,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...gs};return{...gs,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Bc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await Xv(this.config.logDirectory,$h.F_OK|$h.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Qv(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:cr.from(e);try{if(!gc(this.currentLogFile))await pc(this.currentLogFile,"",{mode:420});if(n=bh(this.currentLogFile,"a",420),Jv(n,a,{flag:"a"}),vh(n),n!==void 0)mc(n),n=void 0;if((await Jr(this.currentLogFile)).size===0){if(await pc(this.currentLogFile,a,{flag:"w",mode:420}),(await Jr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{mc(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Xr(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 Xr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Xr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ae())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return dc(16).toString("hex")}generateKey(){return dc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=dc(16),i=zv("aes-256-gcm",t,r),n=cr.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:cr.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ch(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(cr.from(cr.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ae())return;let e=await Jr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Zn(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Jr(r).catch(()=>null))try{if(await xh(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await es(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await pc(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Jr(r).catch(()=>null))await xh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Zn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await es(Xr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=wh(e),i=qv(t),n=Ch();await Zv(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),gc(this.currentLogFile))try{let e=bh(this.currentLogFile,"r+");vh(e),mc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ae()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Zn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await es(Xr(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?Z.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=Re.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${Z.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!ae()){let l=hd[e],u=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:Z.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:Z.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
3
|
+
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:Z.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!ae()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
4
|
+
`;if(c)a+=`${c}
|
|
5
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!ae()){let r=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:Z.blue("◐"),tag:r,message:`${Z.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
6
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!ae()){let u=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:Z.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ae())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ss(t,{...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(r),r}createReadStream(){if(ae())throw Error("createReadStream is not supported in browser environments");if(!gc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wh(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=cr.isBuffer(e)?e:cr.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),c=Gv("aes-256-gcm",r,n);return c.setAuthTag(s),cr.concat([c.update(o),c.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ae()}isServerMode(){return!ae()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!ae()){let s=e.split(`
|
|
7
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(a),showTimestamp:!1}))}else if(!ae())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
|
|
8
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(ae())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Z.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();Re.stdin.removeListener("data",r);try{if(typeof Re.stdin.setRawMode==="function")Re.stdin.setRawMode(!1)}catch{}Re.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Re.stdin.setRawMode==="function")Re.stdin.setRawMode(!0)}catch{}Re.stdin.resume(),Re.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!ae()){let o=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",c=Z.blue("◐");console.error(`${c} ${o} ${Z.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
9
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||ae()||e<=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 r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ae())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ae())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ae())return;Re.stdout.write(`${"\r".padEnd(Re.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||ae()||!Re.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=Z.green("━".repeat(i)),o=Z.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?Z.green("✓"):Z.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${Z.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Re.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Re.stdout.write(e.lastRenderedLine),t)Re.stdout.write(`
|
|
10
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ae()||!Re.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ae()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zn(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Xr(this.config.logDirectory,i);if(e.before)try{if((await Jr(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await es(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ds(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&z(t[0])&&"id"in t[0]&&t[0].id===3&&z(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(z(t)&&z(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(z(e)&&"arr"in e&&Array.isArray(e.arr)&&z(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&z(t[0])&&z(e[0])){let i=[...t];for(let n of e)if(z(n)&&"name"in n){if(!i.find((o)=>z(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(z(n)&&"path"in n){if(!i.find((o)=>z(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Es(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!z(t)||!z(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(z(n)&&z(r[i]))r[i]=ds(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&z(n[0])&&z(r[i][0])){let s=[...n];for(let o of r[i])if(z(o)&&"name"in o){if(!s.find((a)=>z(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(z(o)&&"path"in o){if(!s.find((a)=>z(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Es(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Gc(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:ds(e,t);if(Array.isArray(e))return r==="replace"?t:ds(e,t);if(!z(t)||!z(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=ds(o,s);else if(z(s)&&z(o))i[n]=Gc(o,s,r);else i[n]=s}return i}function Es(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Es(e[r],t[r]))return!1;return!0}if(z(e)&&z(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Es(e[n],t[n]))return!1}return!0}return!1}function z(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function ls(e,t,r="replace"){if(!Zh(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Gc(t,n,r)}catch{return null}}catch{return null}}function Mb(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,y=`${i}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)ke.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=Xi.env[d]||Xi.env[y];if(g!==void 0){if(r)ke.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(n)}async function Ib({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Mb(e,n,s):n,l=r||Xi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)ke.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ke(l,"config"),Ke(l,".config"),i?Ke(l,i):void 0].filter(Boolean)));for(let p of g){if(s)ke.info(`Searching for configuration in: ${p}`);let b=[Ke(l,"config"),Ke(l,".config")].concat(i?[Ke(l,i)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of b)for(let R of u){let v=Ke(p,`${P}${R}`),T=await ls(v,a,c);if(T!==null){if(s)ke.success(`Configuration loaded from: ${v}`);return T}}}if(e){let p=Ke(hc(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)ke.info(`Checking user config directory: ${p}`);for(let b of w)for(let P of u){let R=Ke(p,`${b}${P}`),v=await ls(R,a,c);if(v!==null){if(s)ke.success(`Configuration loaded from user config directory: ${R}`);return v}}}if(e){let p=Ke(hc(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)ke.info(`Checking user config directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ke(p,`${b}${P}`),v=await ls(R,a,c);if(v!==null){if(s)ke.success(`Configuration loaded from user config directory dotfile: ${R}`);return v}}}if(e){let p=hc(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)ke.info(`Checking user home directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ke(p,`${b}${P}`),v=await ls(R,a,c);if(v!==null){if(s)ke.success(`Configuration loaded from user home directory: ${R}`);return v}}}try{let p=Ke(l,"package.json");if(Zh(p)){let w=await import(p),b=w[e];if(!b&&t){if(b=w[t],b&&s)ke.success(`Using alias "${t}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(s)ke.success(`Configuration loaded from package.json: ${b===w[e]?e:t}`);return Gc(a,b,c)}catch(P){if(s)ke.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)ke.warn("Failed to load package.json:",p)}if(s)ke.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function _b(e,t={}){let r=vs.cwd();while(r.includes("storage"))r=ph(r,"..");let i=ph(r,e||"");if(t?.relative)return Hv(vs.cwd(),i);return i}async function jb(){try{let e=await Ib({name:"clarity",alias:"logging",defaultConfig:ps,cwd:vs.cwd()});return{...ps,...e||{}}}catch{return ps}}function ge(){if(Mt.env.NODE_ENV==="test"||Mt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ub(){if(Mt.env.NODE_ENV==="test"||Mt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Mt<"u"){let e=Mt.type;if(e==="renderer"||e==="worker")return!1;return!!(Mt.versions&&(Mt.versions.node||Mt.versions.bun))}return!1}class id{async format(e){let t=await Ub(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ti.pid,hostname:t(),environment:ti.env.NODE_ENV||"development",platform:ti.platform,version:ti.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ti.env.NODE_ENV||ti.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ts{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(e,t={}){this.name=e,this.config={...Lc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new id,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ys,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ys};return{...ys,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Lc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ge()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await nb(this.config.logDirectory,Ph.F_OK|Ph.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await sb(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ft.from(e);try{if(!ts(this.currentLogFile))await vc(this.currentLogFile,"",{mode:420});if(n=Th(this.currentLogFile,"a",420),ib(n,a,{flag:"a"}),Eh(n),n!==void 0)wc(n),n=void 0;if((await Zr(this.currentLogFile)).size===0){if(await vc(this.currentLogFile,a,{flag:"w",mode:420}),(await Zr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{wc(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 ei(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 ei(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ei(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ge())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return yc(16).toString("hex")}generateKey(){return yc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yc(16),i=eb("aes-256-gcm",t,r),n=Ft.isBuffer(e)?e:Ft.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Ft.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Ah(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Ft.from(Ft.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ge())return;if(!this.shouldWriteToFile())return;let e=await Zr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await rs(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Zr(r).catch(()=>null))try{if(await Rh(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await is(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await vc(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Zr(r).catch(()=>null))await Rh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await rs(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await is(ei(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Sh(e),i=rb(t),n=Ah();await cb(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),ts(this.currentLogFile))try{let e=Th(this.currentLogFile,"r+");Eh(e),wc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ge()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await rs(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await is(ei(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?_.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ge())return!1;let e=typeof F.env.NO_COLOR<"u",t=F.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=F.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${_.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=_.underline(_.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>_.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>_.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>_.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>_.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>_.strikethrough(i)),t}supportsHyperlinks(){if(ge())return!1;let e=F.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=F.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ob(t)||t.startsWith("./")||t.startsWith("../"))t=ab(t);else return null;return ts(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":dd[e],h=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:_.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:_.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
11
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:_.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!ge()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
12
|
+
`;if(c)u+=`${c}
|
|
13
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ge()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!ge()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!ge()&&F.stdout.isTTY)F.stdout.write(`
|
|
14
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!ge()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":_.blue("◐"),tag:r,message:`${_.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
15
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":_.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ge())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ts(t,{...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(r),r}createReadStream(){if(ge())throw Error("createReadStream is not supported in browser environments");if(!ts(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Sh(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Ft.isBuffer(e)?e:Ft.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),c=tb("aes-256-gcm",r,n);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Ft.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ge()}isServerMode(){return!ge()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
16
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:_.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:_.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:_.cyan(u),showTimestamp:!1}))}else if(!ge())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
17
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(ge())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${_.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();F.stdin.removeListener("data",r);try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!1)}catch{}F.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!0)}catch{}F.stdin.resume(),F.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${_.blue("◐")} `;console.error(`${l}${a} ${_.cyan(i)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
18
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=_.green("━".repeat(i)),o=_.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?_.green("✓"):_.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${_.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=F.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,F.stdout.write(e.lastRenderedLine),t)F.stdout.write(`
|
|
19
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ge()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ge()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await rs(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=ei(this.config.logDirectory,i);if(e.before)try{if((await Zr(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await is(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function nd(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function sd(e){return e instanceof et}function Wb(e){return e instanceof Ps}function Kb(e){if(sd(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ds{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return en.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),a=`${r}_${c.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=ns.env[a]||(l?ns.env[l]:void 0);if(u!==void 0){if(i.verbose){let f=ns.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof s,a,i.customParsers,i.configName)}catch(f){if(f instanceof Rs)throw f;throw lr.envVar(a,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw lr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(ns.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
20
20
|
|
|
21
|
-
`;for(let
|
|
22
|
-
`,
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
21
|
+
`;for(let i of e)r+=`${i.key}
|
|
22
|
+
`,r+=` Type: ${i.type}
|
|
23
|
+
`,r+=` Description: ${i.description}
|
|
24
|
+
`,r+=` Example: ${i.example}
|
|
25
25
|
|
|
26
|
-
`;return
|
|
26
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
27
27
|
|
|
28
|
-
`;
|
|
29
|
-
`,
|
|
30
|
-
`;for(let
|
|
31
|
-
`;return Y}}function JK(w,$){let Y=Kz("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function zz(w,$,Y={}){return fz(w,$,Y,new WeakMap)}function fz(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 Bz(w,$,X,A);if(!Qw($)||!Qw(w))return $;return QK(w,$,Y,A)}function Bz(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 UK(w,$);case"smart":return WK(w,$,A);default:return $}return $}function UK(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>iJ(X,A)))Y.push(A);return Y}function WK(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Qw($[0])&&Qw(w[0]))return jK(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 jK(w,$,Y){let A=[...$];for(let X of w){if(!Qw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Qw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function QK(w,$,Y,A){let X=$;if(Qw(X)&&A.has(X))return A.get(X);let J={...w};if(Qw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let 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(Qw(j)&&Qw(W))J[U]=fz(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Bz(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function oJ(w,$,Y="replace"){return zz(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(Qw(w)&&Qw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!iJ(w[X],$[X]))return!1}return!0}return!1}function Qw(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=J1.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()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new o1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new o1(w,Error("Configuration must export a valid object"),"unknown");let E={config:oJ($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)J1.setWithFileCheck("file",E,w,J);return E}catch(Q){throw Q instanceof Error?Q$.configLoad(w,Q):Q$.configLoad(w,Error(String(Q)))}};if(U)return wY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(IJ($,`${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 jz(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=IJ(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=IJ(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 z=[],f=[],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 z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await wY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!y5($))throw new e1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new e1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,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:qz},{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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(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||z))throw W;if(f&&(!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:z=!1}=w,f=J||S$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(g0(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw Q$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?a1(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Nw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),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?a1(w,Y,X):Y,j=[g0(t$(),".config",w),g0(t$(),".config"),t$()];for(let W of j){if(X)Nw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Nw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?a1(w,A,J):A;try{let W=g0(Y,"package.json");if(!ZJ(W))return null;let Q=await import(W),z=Q[w],f=w;if(!z&&$)z=Q[$],f=$;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Nw.success(`Configuration loaded from package.json: ${f}`);return{config:oJ(j,z,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:a1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Q$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return J1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);J1.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(t$(),".config",w),g0(t$(),".config"),t$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}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 zK(w){return uw.loadConfig({...w,__strictErrorHandling:!0})}async function Gz(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)Nw.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 fK(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||S$.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 BK(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 a1(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,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=S$.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function GK(w){let $=g0(S$.cwd(),w.configDir),Y=g0(S$.cwd(),w.generatedDir),A=g0(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${mK}
|
|
32
|
-
export type ConfigNames = ${
|
|
33
|
-
`;
|
|
34
|
-
${
|
|
28
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
29
|
+
`,r+=`|----------|------|-------------|----------|
|
|
30
|
+
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
31
|
+
`;return r}}function Hb(e,t){let r=ud("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function od(e,t,r={}){return ad(e,t,r,new WeakMap)}function ad(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return cd(e,t,n,i);if(!ut(t)||!ut(e))return t;return Gb(e,t,r,i)}function cd(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return Vb(e,t);case"smart":return Yb(e,t,i);default:return t}return t}function Vb(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Fc(n,i)))r.push(i);return r}function Yb(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ut(t[0])&&ut(e[0]))return zb(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function zb(e,t,r){let i=[...t];for(let n of e){if(!ut(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((l)=>ut(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function Gb(e,t,r,i){let n=t;if(ut(n)&&i.has(n))return i.get(n);let s={...e};if(ut(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(ut(c)&&ut(a))s[o]=ad(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=cd(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function qc(e,t,r="replace"){return od(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Fc(e[r],t[r]))return!1;return!0}if(ut(e)&&ut(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Fc(e[n],t[n]))return!1}return!0}return!1}function ut(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Fs{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=si.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!ss(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new Qi(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new Qi(e,Error("Configuration must export a valid object"),"unknown");let p={config:qc(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)si.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?lr.configLoad(e,l):lr.configLoad(e,Error(String(l)))}};if(o)return en.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(bc(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return nd(async()=>ss(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!ss(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=bc(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=bc(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!ss(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Jc{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await en.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!lb(t))throw new Zi(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Zi(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:gd},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xc{fileLoader=new Fs;envProcessor=new Ds;validator=new Jc;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)vt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw vt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Ar.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(He(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw lr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?Ji(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)vt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)vt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Ji(e,r,n):r,c=[He(qr(),".config",e),He(qr(),".config"),qr()];for(let a of c){if(n)vt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?Ji(e,i,s):i;try{let a=He(r,"package.json");if(!Nc(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)vt.success(`Configuration loaded from package.json: ${f}`);return{config:qc(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)vt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ji(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw lr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return si.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);si.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,He(e,"config"),He(e,".config"),t?He(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(He(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[He(qr(),".config",e),He(qr(),".config"),qr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Ih(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||i}async function qb(e){return _t.loadConfig({...e,__strictErrorHandling:!0})}async function ld(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await _t.loadConfig(e);else i=await _t.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)vt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await _t.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function Jb(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await _t.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ih(r)))return(await _t.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await _t.loadConfig({...e,cwd:e.cwd||Ar.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ih(t)))return(await _t.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function Xb(e,t,r="replace"){let i=new Fs;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Ji(e,t,r=!1){let i=new Ds,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Ar.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function Qb(e){let t=He(Ar.cwd(),e.configDir),r=He(Ar.cwd(),e.generatedDir),i=He(r,"config-types.ts");if(!Nc(gh(i)))jv(gh(i),{recursive:!0,mode:511});let n=Nc(t)?Uv(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${P$}
|
|
32
|
+
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
33
|
+
`;Wv(i,s,{mode:438})}function Zb(e){let t=null,r=null,i=()=>{if(!r)r=ld(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)vt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let c=n[o];return i(),c},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,c){if(!t)t={...n};return t[o]=c,!0}})}function e$(e){let t=kh(hb.cwd(),e?.configDir||"./config");function r(){if(!ub(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=fb(t).filter((a)=>n.has($c(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=$c(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=$c(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=n.length?`{
|
|
34
|
+
${n.map((l)=>{let u=kh(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
|
|
35
35
|
`)}
|
|
36
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
37
|
-
export type ConfigByName = ${
|
|
36
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
37
|
+
export type ConfigByName = ${c}
|
|
38
38
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
39
39
|
export type ConfigOf = Config
|
|
40
|
-
`}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function dK(w,$={}){let Y=yA.cwd();while(Y.includes("storage"))Y=ZQ(Y,"..");let A=ZQ(Y,w||"");if($?.relative)return S5(yA.cwd(),A);return A}function E0(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lK(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bw<"u"){let w=bw.type;if(w==="renderer"||w==="worker")return!1;return!!(bw.versions&&(bw.versions.node||bw.versions.bun))}return!1}class Iz{async format(w){let $=await lK(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:X1.pid,hostname:$(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iA{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={...hA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Iz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...DJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...DJ};return{...DJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:hA.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 k5(this.config.logDirectory,uQ.F_OK|uQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Z5(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:Zw.from(w);try{if(!jA(this.currentLogFile))await LJ(this.currentLogFile,"",{mode:420});if(X=bQ(this.currentLogFile,"a",420),x5(X,W,{flag:"a"}),iQ(X),X!==void 0)VJ(X),X=void 0;if((await Y1(this.currentLogFile)).size===0){if(await LJ(this.currentLogFile,W,{flag:"w",mode:420}),(await Y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{VJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,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 A1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return A1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(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 CJ(16).toString("hex")}generateKey(){return CJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let 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=CJ(16),A=_5("aes-256-gcm",$,Y),X=Zw.isBuffer(w)?w:Zw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=Zw.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=cQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Zw.from(Zw.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 Y1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await QA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await Y1(Y).catch(()=>null))try{if(await vQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await zA(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 LJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await Y1(Y).catch(()=>null))await vQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await QA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await zA(A1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=PQ(w),A=D5($),X=cQ();await b5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),jA(this.currentLogFile))try{let w=bQ(this.currentLogFile,"r+");iQ(w),VJ(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 QA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await zA(A1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof k.env.NO_COLOR<"u",$=k.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,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=k.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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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(E0())return!1;let w=k.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=k.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(P5($)||$.startsWith("./")||$.startsWith("../"))$=i5($);else return null;return jA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,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 f=this.options.showIcons===!1?"":sK[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:f,tag:B,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
41
|
-
`);for(let
|
|
42
|
-
`;if(
|
|
43
|
-
`;if(
|
|
44
|
-
`);if(this[
|
|
45
|
-
`,
|
|
46
|
-
`),
|
|
47
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
48
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
49
|
-
`)}finishProgressBar(
|
|
40
|
+
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}function A$(e,t={}){let r=xs.cwd();while(r.includes("storage"))r=Oh(r,"..");let i=Oh(r,e||"");if(t?.relative)return mb(xs.cwd(),i);return i}function ye(){if(It.env.NODE_ENV==="test"||It.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function O$(){if(It.env.NODE_ENV==="test"||It.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof It<"u"){let e=It.type;if(e==="renderer"||e==="worker")return!1;return!!(It.versions&&(It.versions.node||It.versions.bun))}return!1}class vd{async format(e){let t=await O$(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ni.pid,hostname:t(),environment:ni.env.NODE_ENV||"development",platform:ni.platform,version:ni.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ni.env.NODE_ENV||ni.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bs{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(e,t={}){this.name=e,this.config={...As},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new vd,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??B.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Ac,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Ac};return{...Ac,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:As.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ye()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await vb(this.config.logDirectory,Bh.F_OK|Bh.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await bb(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Bt.from(e);try{if(!os(this.currentLogFile))await Sc(this.currentLogFile,"",{mode:420});if(n=Fh(this.currentLogFile,"a",420),wb(n,a,{flag:"a"}),Dh(n),n!==void 0)Cc(n),n=void 0;if((await ri(this.currentLogFile)).size===0){if(await Sc(this.currentLogFile,a,{flag:"w",mode:420}),(await ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{Cc(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 ii(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 ii(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return ii(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ye())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return xc(16).toString("hex")}generateKey(){return xc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=xc(16),i=gb("aes-256-gcm",t,r),n=Bt.isBuffer(e)?e:Bt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Bt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Mh(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Bt.from(Bt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ye())return;if(!this.shouldWriteToFile())return;let e=await ri(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await as(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await ri(r).catch(()=>null))try{if(await Lh(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await cs(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Sc(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await ri(r).catch(()=>null))await Lh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await as(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await cs(ii(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Nh(e),i=yb(t),n=Mh();await Cb(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),os(this.currentLogFile))try{let e=Fh(this.currentLogFile,"r+");Dh(e),Cc(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ye()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await as(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await cs(ii(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?K.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ye())return!1;let e=typeof B.env.NO_COLOR<"u",t=B.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof B.stderr<"u"&&B.stderr.isTTY||typeof B.stdout<"u"&&B.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=B.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${K.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=K.underline(K.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>K.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>K.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>K.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>K.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>K.strikethrough(i)),t}supportsHyperlinks(){if(ye())return!1;let e=B.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=B.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if($b(t)||t.startsWith("./")||t.startsWith("../"))t=xb(t);else return null;return os(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":L$[e],h=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:K.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:K.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
41
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:K.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!ye()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
42
|
+
`;if(c)u+=`${c}
|
|
43
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ye()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!ye()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!ye()&&B.stdout.isTTY)B.stdout.write(`
|
|
44
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!ye()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:r,message:`${K.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
45
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":K.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ye())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Bs(t,{...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(r),r}createReadStream(){if(ye())throw Error("createReadStream is not supported in browser environments");if(!os(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Nh(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Bt.isBuffer(e)?e:Bt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),c=pb("aes-256-gcm",r,n);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Bt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ye()}isServerMode(){return!ye()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
46
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:K.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(u),showTimestamp:!1}))}else if(!ye())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
47
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(ye())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();B.stdin.removeListener("data",r);try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!1)}catch{}B.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!0)}catch{}B.stdin.resume(),B.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${l}${a} ${K.cyan(i)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
48
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!B.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=K.green("━".repeat(i)),o=K.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?K.green("✓"):K.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=B.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,B.stdout.write(e.lastRenderedLine),t)B.stdout.write(`
|
|
49
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ye()||!B.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ye()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await as(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=ii(this.config.logDirectory,i);if(e.before)try{if((await ri(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await cs(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function M$(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class Zc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Hc.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),a=`${r}_${c.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=us.env[a]||(l?us.env[l]:void 0);if(u!==void 0){if(i.verbose){let f=us.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof s,a,i.customParsers,i.configName)}catch(f){if(f instanceof Qc)throw f;throw oi.envVar(a,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw oi.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(us.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
50
50
|
|
|
51
|
-
`;for(let
|
|
52
|
-
`,
|
|
53
|
-
`,
|
|
54
|
-
`,
|
|
51
|
+
`;for(let i of e)r+=`${i.key}
|
|
52
|
+
`,r+=` Type: ${i.type}
|
|
53
|
+
`,r+=` Description: ${i.description}
|
|
54
|
+
`,r+=` Example: ${i.example}
|
|
55
55
|
|
|
56
|
-
`;return
|
|
56
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
57
57
|
|
|
58
|
-
`;
|
|
59
|
-
`,
|
|
60
|
-
`;for(let
|
|
61
|
-
`;return Y}}function eK(w,$,Y={}){return hz(w,$,Y,new WeakMap)}function hz(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 Dz(w,$,X,A);if(!zw($)||!zw(w))return $;return AF(w,$,Y,A)}function Dz(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 wF(w,$);case"smart":return $F(w,$,A);default:return $}return $}function wF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>lJ(X,A)))Y.push(A);return Y}function $F(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return YF(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 YF(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((Q)=>zw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function AF(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]=hz(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Dz(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function xz(w,$,Y="replace"){return eK(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(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(!lJ(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class kz{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()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new DA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new DA(w,Error("Configuration must export a valid object"),"unknown");let E={config:xz($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)HA.setWithFileCheck("file",E,w,J);return E}catch(Q){throw Q instanceof Error?U1.configLoad(w,Q):U1.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 oK(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 Zz{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 z=[],f=[],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 z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await pJ.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!XF($))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:JF},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function UF(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 Pz{fileLoader=new kz;envProcessor=new YU;validator=new Zz;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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(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||z))throw W;if(f&&(!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)Sw.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 Sw.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:z=!1}=w,f=J||kA.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(jw(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw U1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${UF(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?KA(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Sw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Sw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?KA(w,Y,X):Y,j=[jw(r$(),".config",w),jw(r$(),".config"),r$()];for(let W of j){if(X)Sw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Sw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?KA(w,A,J):A;try{let W=jw(Y,"package.json");if(!eG(W))return null;let Q={};try{Q=JSON.parse(w5(W,"utf8"))}catch(B){if(J)Sw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let z=Q[w],f=w;if(!z&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){z=Q[G],f=G;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Sw.success(`Configuration loaded from package.json: ${f}`);return{config:xz(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Sw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:KA(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 U1.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,jw(w,"config"),jw(w,".config"),$?jw(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(jw(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=[jw(r$(),".config",w),jw(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)}}async function iz(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)Sw.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 KA(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,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=kA.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}var HA,pJ,u5,v5=(w)=>w,m5=(w,$)=>{for(var Y in $)u5(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:c5.bind($,Y)})},g5=(w,$)=>()=>(w&&($=w(w=0)),$),Jz,Kz,J1,wY,Fz,EK,TK,gQ,EA,bJ,O0,o,NK,dQ,qK,nQ,HK,RK,OJ,MK,lQ,pQ,SJ,IK,yK,CK,VK,TA,Ez,LK,S0,OK,SK,rQ,NA,uJ,F0,b,_K,tQ,hK,aQ,DK,xK,_J,kK,sQ,oQ,ZK,hJ,PK,iK,bK,uK,vK,qA,Tz,cK,mK="0.15.6",e0,SA,o1,vJ,cJ,_A,mJ,gJ,e1,dJ,nJ,Q$,Nz,qz,Nw,uw,Hz,Rz,gK,nK,Mz,hA,XI,I0,c,JI,pK,UI,rK,WI,jI,eQ,QI,tK,aK,zI,wz,fI,BI,GI,KI,FI,DJ,sK,EI,qw,yz,DA,Cz,Vz,$U,Lz,Oz,xA,Sz,_z,U1,JF,Sw,kJ,RI,MI;var bz=s(()=>{HA=new $z,pJ=new Yz,u5=Object.defineProperty;Jz={};m5(Jz,{withErrorRecovery:()=>jz,tryLoadConfig:()=>BK,loadConfigWithResult:()=>zK,loadConfig:()=>Gz,isRetryableError:()=>XK,isConfigNotFoundError:()=>AK,isBunfigError:()=>Qz,globalPerformanceMonitor:()=>wY,globalCache:()=>J1,getEnvOrDefault:()=>JK,generateConfigTypes:()=>GK,defaultGeneratedDir:()=>Rz,defaultConfigDir:()=>Hz,deepMergeWithArrayStrategy:()=>oJ,deepMerge:()=>zz,createLibraryConfig:()=>KK,config:()=>fK,bunfigPlugin:()=>FK,applyEnvVarsToConfig:()=>a1,TypeGenerationError:()=>gJ,SchemaValidationError:()=>e1,PluginError:()=>nJ,PerformanceMonitor:()=>tJ,FileSystemError:()=>mJ,ErrorFactory:()=>Q$,EnvVarError:()=>_A,EnvProcessor:()=>ZA,ConfigValidator:()=>eJ,ConfigValidationError:()=>vJ,ConfigNotFoundError:()=>SA,ConfigMergeError:()=>cJ,ConfigLoader:()=>wU,ConfigLoadError:()=>o1,ConfigFileLoader:()=>PA,ConfigCache:()=>rJ,CacheUtils:()=>Fz,BunfigError:()=>e0,BrowserConfigError:()=>dJ,ArrayMergeStrategies:()=>Nz});gK=g5(async()=>{Kz=import.meta.require,J1=new rJ,wY=new tJ,Fz={createKey:d5,isEquivalent:n5,estimateMemoryUsage:l5},EK=IA(PJ.cwd(),"config"),TK=IA(PJ.cwd(),"src/generated"),gQ=MA.env.CLARITY_LOG_DIR||U5(t5(),"logs"),EA={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(),O0={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=O0,NK=O0.red,dQ=O0.green,qK=O0.yellow,nQ=O0.blue,HK=O0.magenta,RK=O0.cyan,OJ=O0.white,MK=O0.gray,lQ=O0.bgRed,pQ=O0.bgYellow,SJ=O0.bold,IK=O0.dim,yK=O0.italic,CK=O0.underline,VK=O0.reset,TA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ez={debug:"\uD83D\uDD0D",info:nQ("ℹ"),success:dQ("✓"),warning:pQ(OJ(SJ(" WARN "))),error:lQ(OJ(SJ(" ERROR ")))},LK=new VA("stacks"),S0=new VA("bunfig",{showTags:!0}),OK=m0(s1.cwd(),"config"),SK=m0(s1.cwd(),"src/generated"),rQ=RA.env.CLARITY_LOG_DIR||X5(wK(),"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 $K(),F0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=F0,_K=F0.red,tQ=F0.green,hK=F0.yellow,aQ=F0.blue,DK=F0.magenta,xK=F0.cyan,_J=F0.white,kK=F0.gray,sQ=F0.bgRed,oQ=F0.bgYellow,ZK=F0.bgGray,hJ=F0.bold,PK=F0.dim,iK=F0.italic,bK=F0.underline,uK=F0.strikethrough,vK=F0.reset,qA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tz={debug:"\uD83D\uDD0D",info:aQ("ℹ"),success:tQ("✓"),warning:oQ(_J(hJ(" WARN "))),error:sQ(_J(hJ(" ERROR ")))},cK=new OA("stacks"),e0=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}${$}`}},SA=class extends e0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},o1=class extends e0{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}},vJ=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},cJ=class extends e0{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}},_A=class extends e0{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 e0{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 e0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},e1=class extends e0{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 e0{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 e0{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 SA(w,$,Y)},configLoad(w,$,Y){return new o1(w,$,Y)},configValidation(w,$,Y){return new vJ(w,$,Y)},configMerge(w,$,Y,A){return new cJ(w,$,Y,A)},envVar(w,$,Y,A){return new _A(w,$,Y,A)},fileSystem(w,$,Y){return new mJ(w,$,Y)},typeGeneration(w,$,Y){return new gJ(w,$,Y)},schemaValidation(w,$,Y){return new e1(w,$,Y)},browserConfig(w,$,Y,A){return new dJ(w,$,Y,A)},plugin(w,$,Y){return new nJ(w,$,Y)}},Nz={replace:"replace",concat:"concat",smart:"smart"},qz=/^https?:\/\//,Nw=new OA("bunfig",{showTags:!0}),uw=new wU,Hz=g0(S$.cwd(),"config"),Rz=g0(S$.cwd(),"src/generated")});nK=yA.env.CLARITY_LOG_DIR||O5(dK(),"logs"),Mz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:nK,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},hA={...Mz},XI=(async()=>{try{let{loadConfig:w}=await gK().then(()=>Jz),$=await w({name:"clarity",alias:"logging",defaultConfig:Mz,cwd:yA.cwd()});if($)Object.assign(hA,$)}catch{}return hA})();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"},c=I0,JI=I0.red,pK=I0.green,UI=I0.yellow,rK=I0.blue,WI=I0.magenta,jI=I0.cyan,eQ=I0.white,QI=I0.gray,tK=I0.bgRed,aK=I0.bgYellow,zI=I0.bgGray,wz=I0.bold,fI=I0.dim,BI=I0.italic,GI=I0.underline,KI=I0.strikethrough,FI=I0.reset,DJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sK={debug:"\uD83D\uDD0D",info:rK("ℹ"),success:pK("✓"),warning:aK(eQ(wz(" WARN "))),error:tK(eQ(wz(" ERROR ")))};EI=new iA("stacks");qw=class qw 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}`}};yz=class yz extends qw{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 qw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};Cz=class Cz extends qw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Vz=class Vz extends qw{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 qw{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})}};Lz=class Lz extends qw{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}};Oz=class Oz extends qw{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 qw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Sz=class Sz extends qw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};_z=class _z extends qw{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}};U1={configNotFound(w,$,Y){return new yz(w,$,Y)},configLoad(w,$,Y){return new DA(w,$,Y)},configValidation(w,$,Y){return new Cz(w,$,Y)},configMerge(w,$,Y,A){return new Vz(w,$,Y,A)},envVar(w,$,Y,A){return new $U(w,$,Y,A)},fileSystem(w,$,Y){return new Lz(w,$,Y)},typeGeneration(w,$,Y){return new Oz(w,$,Y)},schemaValidation(w,$,Y){return new xA(w,$,Y)},browserConfig(w,$,Y,A){return new Sz(w,$,Y,A)},plugin(w,$,Y){return new _z(w,$,Y)}};JF=/^https?:\/\//;Sw=new iA("bunfig",{showTags:!0});kJ=new Pz;RI=jw(kA.cwd(),"config"),MI=jw(kA.cwd(),"src/generated")});import{homedir as AU}from"node:os";import{join as XU,resolve as WF}from"node:path";async function vz(){if(!JU)JU=await iz({name:"rpx",cwd:WF(__dirname,".."),defaultConfig:uz});return JU}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",uz,JU=null,vw;var bA=s(()=>{bz();uz={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};vw=uz});function W1(w){return w.startsWith("*.")}function h$(w,$){if(!W1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function cz(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!W1(J))continue;if(h$($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}import{existsSync as jF,readdirSync as QF,readFileSync as zF,statSync as fF}from"node:fs";import{homedir as gz}from"node:os";import{isAbsolute as BF,join as j1}from"node:path";function WU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return j1($,w.slice(2));return w}function KF(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 FF(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 EF(w,$){let Y=$.readText(j1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(j1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function TF(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 NF(w,$){let Y=EF(w,$);if(Y?.command)return TF(Y);let A=$.fileExists(j1(w,"buddy")),X=$.readText(j1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function jU(w,$={}){let Y={dirExists:$.dirExists??UU.dirExists,fileExists:$.fileExists??UU.fileExists,readText:$.readText??UU.readText},A=$.detect??NF,X=$.homeDir??gz(),J=w.tlds??nz,U=(w.roots??dz).map((B)=>WU(B,X)),j=w.idleTimeoutMs??GF,W=new Map;for(let B of w.sites??[])W.set(B.to,B);let Q=(B)=>B.idleTimeoutMs??j;function z(B){let G=cz(W,B);if(!G)return null;let T=BF(G.dir)?G.dir:WU(G.dir,X),F=G.selfRegisters??!1,E=G.routes??[];if(!F&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let N=mz({...G.env??{}},void 0,B);return{host:B,id:uA(B),dir:T,command:G.command,env:N,routes:E,selfRegisters:F,idleTimeoutMs:Q(G),source:"config"}}function f(B){let G=FF(B,J);if(!G)return null;for(let T of U){let F=j1(T,G);if(!Y.dirExists(F))continue;let E=A(F,Y);if(!E)continue;let N=E.selfRegisters??!1;return{host:B,id:uA(B),dir:F,command:E.command,env:mz({...E.env??{}},E.urlEnv,B),routes:N?[]:E.routes??[],selfRegisters:N,idleTimeoutMs:j,source:"discovered"}}return null}return{resolve(B){let G=KF(B);if(!G)return null;return z(G)??f(G)}}}function qF(w){try{return QF(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function lz(w,$={}){let Y=$.homeDir??gz(),A=w.tlds??nz,X=(w.roots??dz).map((f)=>WU(f,Y)),J=$.readdir??qF,U=jU(w,$),j=[],W=new Set,Q=(f)=>{if(f&&!W.has(f.host))W.add(f.host),j.push(f)};for(let f of w.sites??[])if(!f.to.includes("*"))Q(U.resolve(f.to));let z=A[0]??"localhost";for(let f of X)for(let B of J(f))Q(U.resolve(`${B}.${z}`));return j}function mz(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var dz,nz,GF=1800000,UU;var QU=s(()=>{dz=["~/Code"],nz=["localhost","test"],UU={dirExists:(w)=>{try{return fF(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return jF(w)}catch{return!1}},readText:(w)=>{try{return zF(w,"utf8")}catch{return null}}}});var H;var D$=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 HF}from"node:module";import{Resolver as zU}from"node:dns/promises";import{createHash as MF,sign as IF}from"node:crypto";import{createHash as yF}from"node:crypto";import{sign as CF}from"node:crypto";import{generateKeyPairSync as ef,X509Certificate as kF}from"node:crypto";import fU from"node:os";import BU from"node:path";import{existsSync as rz,statSync as tz}from"fs";import{existsSync as PF,mkdirSync as nI,readdirSync as lI,readFileSync as iF,writeFileSync as pI}from"fs";import{homedir as Q1}from"os";import{dirname as aI,resolve as Bw}from"path";import VX from"process";import{existsSync as az,statSync as sz}from"fs";import{existsSync as PU,mkdirSync as bF,readdirSync as uF,writeFileSync as vF}from"fs";import{homedir as z1}from"os";import{dirname as oz,resolve as n0}from"path";import k$ from"process";import{join as cF,relative as mF,resolve as ez}from"path";import QX from"process";import{existsSync as wB,mkdirSync as Uy,readdirSync as Wy,writeFileSync as jy}from"fs";import{homedir as GU}from"os";import{dirname as fy,resolve as d0}from"path";import JY from"process";import{join as gF,relative as dF,resolve as wf}from"path";import zX from"process";import{existsSync as $B,mkdirSync as Ey,readdirSync as Ty,writeFileSync as Ny}from"fs";import{dirname as Hy,resolve as fX}from"path";import iU from"process";import{Buffer as z$}from"buffer";import{createCipheriv as nF,createDecipheriv as lF,randomBytes as KU}from"crypto";import{closeSync as FU,createReadStream as $f,createWriteStream as pF,existsSync as EU,fsyncSync as Yf,openSync as Af,writeFileSync as rF}from"fs";import{access as tF,constants as Xf,mkdir as aF,readdir as vA,rename as Jf,stat as f1,unlink as cA,writeFile as TU}from"fs/promises";import{join as B1}from"path";import _0 from"process";import{pipeline as sF}from"stream/promises";import{createGzip as Uf}from"zlib";import G1 from"process";import dw from"process";import{Buffer as cw}from"buffer";import{createCipheriv as oF,createDecipheriv as eF,randomBytes as NU}from"crypto";import{closeSync as qU,createReadStream as Wf,createWriteStream as wE,existsSync as mA,fsyncSync as jf,openSync as Qf,writeFileSync as $E}from"fs";import{access as YE,constants as zf,mkdir as AE,readdir as gA,rename as ff,stat as K1,unlink as dA,writeFile as HU}from"fs/promises";import{isAbsolute as XE,join as F1,resolve as JE}from"path";import p from"process";import{pipeline as UE}from"stream/promises";import{createGzip as Bf}from"zlib";import E1 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 WE}from"fs";import{existsSync as jE,readdirSync as QE}from"fs";import{extname as MU,resolve as Gf}from"path";import zE from"process";import{join as fE,relative as BE,resolve as Kf}from"path";import BX from"process";import{Buffer as mw}from"buffer";import{createCipheriv as GE,createDecipheriv as KE,randomBytes as IU}from"crypto";import{closeSync as yU,createReadStream as Ff,createWriteStream as FE,existsSync as pA,fsyncSync as Ef,openSync as Tf,writeFileSync as EE}from"fs";import{access as TE,constants as Nf,mkdir as NE,readdir as rA,rename as qf,stat as T1,unlink as tA,writeFile as CU}from"fs/promises";import{isAbsolute as qE,join as N1,resolve as HE}from"path";import r from"process";import{pipeline as RE}from"stream/promises";import{createGzip as Hf}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 ME}from"fs";import{exec as dT}from"node:child_process";import rU from"node:fs";import nT from"node:os";import Hw from"node:path";import iB from"node:process";import{promisify as lT}from"node:util";import I1 from"node:crypto";import pw from"node:fs";import sU from"node:path";import F7 from"node:crypto";import{execSync as N7}from"node:child_process";import yX 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 vf(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let Q=new zU,z=await Q.resolveNs(J),f=(await Promise.all(z.map((B)=>Q.resolve4(B).catch(()=>[])))).flat();if(f.length>0)U=new zU,U.setServers(f)}catch{}let j=Date.now()+A,W=U??new zU;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 cf(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 mf(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return MF("sha256").update($).digest("base64url")}function gf(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=$X(JSON.stringify($)),J=Y===""?"":$X(JSON.stringify(Y)),U=`${X}.${J}`,j=IF("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=cf(w.accountPublicKey),this.thumbprint=mf(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??uf}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=gf({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 z=await U.text();Q=z?JSON.parse(z):{}}if(U.status>=400){let z=Q??{};throw new WX(`ACME request to ${$} failed (HTTP ${U.status}): ${z.type??""} ${z.detail??""}`.trim(),z,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 yF("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 pz(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 pz(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 lf(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
|
|
62
|
-
`,chainPem:""};let
|
|
63
|
-
`,
|
|
64
|
-
`);return{certPem:
|
|
65
|
-
`:""}}function pf(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function pz(w){return new Promise(($)=>setTimeout($,w))}function VF(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]),VF($.length),$])}function rf(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 x$(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 fw(...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 tf(w){return G$(4,w)}function af(w){return G$(12,Buffer.from(w,"utf8"))}function ZU(w,$,Y){let A=128|(Y?32:0)|w;return G$(A,$)}function xF(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 sf(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=fw(xU(fw(x$(_F),af($[0])))),J=fw(fw(x$(LF),x$(OF)),kU(xF(Y))),U=$.map((F)=>ZU(2,Buffer.from(F,"ascii"),!1)),j=fw(...U),W=fw(x$(DF),tf(j)),Q=fw(W),z=fw(x$(hF),xU(Q)),f=ZU(0,z,!0),B=fw(rf(0),X,J,f),G=CF("sha256",B,A),T=fw(x$(SF));return fw(B,T,kU(G))}function of(w){return sf(w).toString("base64url")}function ZF(w){if(w){let{createPrivateKey:X,createPublicKey:J}=RF("node:crypto"),U=X(w),j=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:j,pem:w}}let{privateKey:$,publicKey:Y}=ef("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((f)=>f.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?nf:df),X=ZF(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=[],z=[];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=pf(C.identifier.value),n=J.dns01TxtValue(M.token);await w.dnsProvider.setTxt(D,n),Q.push({name:D,value:n}),await vf(D,n,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(M.token,J.keyAuthorization(M.token)),z.push(M.token);await J.notifyChallengeReady(M.url),await J.pollAuthorization(q,{timeoutMs:w.timeoutMs})}let{privateKey:f,publicKey:B}=ef("ec",{namedCurve:"P-256"}),G=of({domains:$,publicKey:B,privateKey:f});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(j,{timeoutMs:w.timeoutMs}),F=await J.downloadCertificate(T),{certPem:E,chainPem:N}=lf(F),R=N?`${E}${N}`:E,V=f.export({format:"pem",type:"pkcs8"}).toString(),L=new Date(new kF(E).validTo);return{certPem:E,keyPem:V,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:L}}finally{for(let{name:f,value:B}of Q)await w.dnsProvider?.removeTxt(f,B).catch(()=>{});for(let f of z)W.remove(f)}}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(!rz(w))return!0;return tz(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=rz(Y)?tz(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 CE(w,$){this[w]=yE.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(!az(w))return!0;return sz(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=az(Y)?sz(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 OE(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function SE(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function _E(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)=>KX(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)=>KX(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 KX(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(!KX(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(!KX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function hE(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 DE({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=fX(A,`${U}${j}`),Q=await hE(W,Y);if(Q!==null)return Q}try{let U=fX(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 xE(w,$={}){let Y=zX.cwd();while(Y.includes("storage"))Y=wf(Y,"..");let A=wf(Y,w||"");if($?.relative)return dF(zX.cwd(),A);return A}async function kE(){try{let w=await DE({name:"clarity",defaultConfig:AX,cwd:zX.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 ZE(){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 ZE(),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:G1.pid,hostname:$(),environment:G1.env.NODE_ENV||"development",platform:G1.platform,version:G1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:G1.env.NODE_ENV||G1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=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??_0.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 tF(this.config.logDirectory,Xf.F_OK|Xf.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:z$.from(w);try{if(!EU(this.currentLogFile))await TU(this.currentLogFile,"",{mode:420});if(A=Af(this.currentLogFile,"a",420),rF(A,j,{flag:"a"}),Yf(A),A!==void 0)FU(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 z=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let f=U*2**X;await new Promise((B)=>setTimeout(B,f)),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{FU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,z=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),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 B1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return B1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return B1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(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 KU(16).toString("hex")}generateKey(){return KU(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=KU(16),A=nF("aes-256-gcm",$,Y),X=z$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:z$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Uf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(z$.from(z$.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 vA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),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 Jf(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await cA(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 Jf(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await vA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await cA(B1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=$f(w),A=pF($),X=Uf();await sF(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()})),EU(this.currentLogFile))try{let w=Af(this.currentLogFile,"r+");Yf(w),FU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await cA(B1(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=_0.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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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=FB[w],z=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:e.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:e.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f),j){let B=j.split(`
|
|
66
|
-
`);for(let
|
|
67
|
-
`;if(
|
|
68
|
-
`;
|
|
69
|
-
`,
|
|
70
|
-
`),
|
|
71
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
72
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
73
|
-
`)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!_0.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 vA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=B1(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 cA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}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)=>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(!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)=>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 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 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(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(!EX(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 PE(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(B).join("_")}`,T=`${A}_${f.map((F)=>F.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[Q]=J(z,f);else{let F=JY.env[G]||JY.env[T];if(F!==void 0){if(Y)D0.info(`Using environment variable ${F?G:T} for config ${w}.${f.join(".")}`);if(typeof z==="number")W[Q]=Number(F);else if(typeof z==="boolean")W[Q]=F.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(F);if(Array.isArray(E))W[Q]=E;else W[Q]=F.split(",").map((N)=>N.trim())}catch{W[Q]=F.split(",").map((E)=>E.trim())}else W[Q]=F}}}return W}return J(X)}async function iE({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)?PE(w,X,J):X,Q=Y||JY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let f=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([Q,d0(Q,"config"),d0(Q,".config"),A?d0(Q,A):void 0].filter(Boolean)));for(let E of F){if(J)D0.info(`Searching for configuration in: ${E}`);let N=[d0(Q,"config"),d0(Q,".config")].concat(A?[d0(Q,A)]:[]).includes(E)?[...f,...B,...G,...T]:[...B,...f,...T,...G];for(let R of N)for(let V of z){let L=d0(E,`${R}${V}`),q=await oA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from: ${L}`);return q}}}if(w){let E=d0(GU(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${E}`);for(let R of N)for(let V of z){let L=d0(E,`${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 E=d0(GU(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=d0(E,`${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 E=GU(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=d0(E,`${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 E=d0(Q,"package.json");if(wB(E)){let N=await import(E),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(E){if(J)D0.warn("Failed to load package.json:",E)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function bE(w,$={}){let Y=QX.cwd();while(Y.includes("storage"))Y=ez(Y,"..");let A=ez(Y,w||"");if($?.relative)return mF(QX.cwd(),A);return A}async function uE(){try{let w=await iE({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 vE(){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 vE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:E1.pid,hostname:$(),environment:E1.env.NODE_ENV||"development",platform:E1.platform,version:E1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:E1.env.NODE_ENV||E1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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={...vU},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:vU.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 YE(this.config.logDirectory,zf.F_OK|zf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await AE(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:cw.from(w);try{if(!mA(this.currentLogFile))await HU(this.currentLogFile,"",{mode:420});if(A=Qf(this.currentLogFile,"a",420),$E(A,j,{flag:"a"}),jf(A),A!==void 0)qU(A),A=void 0;if((await K1(this.currentLogFile)).size===0){if(await HU(this.currentLogFile,j,{flag:"w",mode:420}),(await K1(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 z=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let f=U*2**X;await new Promise((B)=>setTimeout(B,f)),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,z=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),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 F1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return F1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,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=oF("aes-256-gcm",$,Y),X=cw.isBuffer(w)?w:cw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=cw.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=Bf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(cw.from(cw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await K1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await K1(Y).catch(()=>null))try{if(await ff(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 K1(Y).catch(()=>null))await ff(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(F1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Wf(w),A=wE($),X=Bf();await UE(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=Qf(this.currentLogFile,"r+");jf(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(F1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof 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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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(XE($)||$.startsWith("./")||$.startsWith("../"))$=JE($);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 f=this.options.showIcons===!1?"":EB[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:f,tag:B,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
74
|
-
`);for(let
|
|
75
|
-
`;if(
|
|
76
|
-
`;if(
|
|
77
|
-
`);if(this[
|
|
78
|
-
`,
|
|
79
|
-
`),
|
|
80
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
81
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
82
|
-
`)}finishProgressBar(
|
|
58
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
59
|
+
`,r+=`|----------|------|-------------|----------|
|
|
60
|
+
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
61
|
+
`;return r}}function I$(e,t,r={}){return Pd(e,t,r,new WeakMap)}function Pd(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Rd(e,t,n,i);if(!ft(t)||!ft(e))return t;return W$(e,t,r,i)}function Rd(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return _$(e,t);case"smart":return j$(e,t,i);default:return t}return t}function _$(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Kc(n,i)))r.push(i);return r}function j$(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(ft(t[0])&&ft(e[0]))return U$(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function U$(e,t,r){let i=[...t];for(let n of e){if(!ft(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((l)=>ft(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function W$(e,t,r,i){let n=t;if(ft(n)&&i.has(n))return i.get(n);let s={...e};if(ft(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(ft(c)&&ft(a))s[o]=Pd(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=Rd(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function Ad(e,t,r="replace"){return I$(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Kc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Kc(e[r],t[r]))return!1;return!0}if(ft(e)&&ft(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Kc(e[n],t[n]))return!1}return!0}return!1}function ft(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class kd{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=ws.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!fs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new ks(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new ks(e,Error("Configuration must export a valid object"),"unknown");let p={config:Ad(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)ws.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?oi.configLoad(e,l):oi.configLoad(e,Error(String(l)))}};if(o)return Hc.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(kc(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return M$(async()=>fs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!fs(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=kc(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=kc(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!fs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Od{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Hc.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!K$(t))throw new Os(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Os(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:H$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function V$(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Nd{fileLoader=new kd;envProcessor=new Zc;validator=new Od;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)kt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw kt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Ns.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(lt(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw oi.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${V$(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?hs(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)kt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)kt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?hs(e,r,n):r,c=[lt(Gr(),".config",e),lt(Gr(),".config"),Gr()];for(let a of c){if(n)kt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?hs(e,i,s):i;try{let a=lt(r,"package.json");if(!Iv(a))return null;let l={};try{l=JSON.parse(_v(a,"utf8"))}catch(h){if(s)kt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)kt.success(`Configuration loaded from package.json: ${f}`);return{config:Ad(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)kt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:hs(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw oi.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return ws.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);ws.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,lt(e,"config"),lt(e,".config"),t?lt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(lt(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[lt(Gr(),".config",e),lt(Gr(),".config"),Gr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}async function Dd(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await Oc.loadConfig(e);else i=await Oc.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)kt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Oc.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}function hs(e,t,r=!1){let i=new Zc,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Ns.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}var ws,Hc,Sb,Eb=(e)=>e,Pb=(e,t)=>{for(var r in t)Sb(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Tb.bind(t,r)})},Rb=(e,t)=>()=>(e&&(t=e(e=0)),t),td,ud,si,en,fd,t$,r$,_h,ms,Bc,Ae,Z,i$,jh,n$,Uh,s$,o$,Ec,a$,Wh,Kh,Tc,c$,l$,u$,f$,gs,hd,h$,ke,d$,m$,Hh,ps,Lc,pe,_,g$,Vh,p$,Yh,y$,w$,Pc,v$,zh,Gh,b$,Rc,$$,x$,C$,S$,E$,ys,dd,T$,P$="0.15.6",et,Ps,Qi,Mc,Ic,Rs,_c,jc,Zi,Uc,Wc,lr,md,gd,vt,_t,pd,yd,R$,k$,wd,As,V1,Se,K,Y1,N$,z1,D$,G1,q1,qh,J1,F$,B$,X1,Jh,Q1,Z1,ek,tk,rk,Ac,L$,ik,bt,bd,ks,$d,xd,Qc,Cd,Sd,Os,Ed,Td,oi,H$,kt,Oc,ck,lk;var Fd=Q(()=>{ws=new Xh,Hc=new Qh,Sb=Object.defineProperty;td={};Pb(td,{withErrorRecovery:()=>nd,tryLoadConfig:()=>Xb,loadConfigWithResult:()=>qb,loadConfig:()=>ld,isRetryableError:()=>Kb,isConfigNotFoundError:()=>Wb,isBunfigError:()=>sd,globalPerformanceMonitor:()=>en,globalCache:()=>si,getEnvOrDefault:()=>Hb,generateConfigTypes:()=>Qb,defaultGeneratedDir:()=>yd,defaultConfigDir:()=>pd,deepMergeWithArrayStrategy:()=>qc,deepMerge:()=>od,createLibraryConfig:()=>Zb,config:()=>Jb,bunfigPlugin:()=>e$,applyEnvVarsToConfig:()=>Ji,TypeGenerationError:()=>jc,SchemaValidationError:()=>Zi,PluginError:()=>Wc,PerformanceMonitor:()=>Yc,FileSystemError:()=>_c,ErrorFactory:()=>lr,EnvVarError:()=>Rs,EnvProcessor:()=>Ds,ConfigValidator:()=>Jc,ConfigValidationError:()=>Mc,ConfigNotFoundError:()=>Ps,ConfigMergeError:()=>Ic,ConfigLoader:()=>Xc,ConfigLoadError:()=>Qi,ConfigFileLoader:()=>Fs,ConfigCache:()=>Vc,CacheUtils:()=>fd,BunfigError:()=>et,BrowserConfigError:()=>Uc,ArrayMergeStrategies:()=>md});R$=Rb(async()=>{ud=import.meta.require,si=new Vc,en=new Yc,fd={createKey:Ab,isEquivalent:kb,estimateMemoryUsage:Ob},t$=$s(Dc.cwd(),"config"),r$=$s(Dc.cwd(),"src/generated"),_h=bs.env.CLARITY_LOG_DIR||Vv(Fb(),"logs"),ms={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_h,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Bc=await Bb(),Ae={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},Z=Ae,i$=Ae.red,jh=Ae.green,n$=Ae.yellow,Uh=Ae.blue,s$=Ae.magenta,o$=Ae.cyan,Ec=Ae.white,a$=Ae.gray,Wh=Ae.bgRed,Kh=Ae.bgYellow,Tc=Ae.bold,c$=Ae.dim,l$=Ae.italic,u$=Ae.underline,f$=Ae.reset,gs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hd={debug:"\uD83D\uDD0D",info:Uh("ℹ"),success:jh("✓"),warning:Kh(Ec(Tc(" WARN "))),error:Wh(Ec(Tc(" ERROR ")))},h$=new Ss("stacks"),ke=new Ss("bunfig",{showTags:!0}),d$=Ke(Xi.cwd(),"config"),m$=Ke(Xi.cwd(),"src/generated"),Hh=vs.env.CLARITY_LOG_DIR||Kv(_b(),"logs"),ps={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Hh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lc=await jb(),pe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},_=pe,g$=pe.red,Vh=pe.green,p$=pe.yellow,Yh=pe.blue,y$=pe.magenta,w$=pe.cyan,Pc=pe.white,v$=pe.gray,zh=pe.bgRed,Gh=pe.bgYellow,b$=pe.bgGray,Rc=pe.bold,$$=pe.dim,x$=pe.italic,C$=pe.underline,S$=pe.strikethrough,E$=pe.reset,ys={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dd={debug:"\uD83D\uDD0D",info:Yh("ℹ"),success:Vh("✓"),warning:Gh(Pc(Rc(" WARN "))),error:zh(Pc(Rc(" ERROR ")))},T$=new Ts("stacks"),et=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,i])=>`${r}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Ps=class extends et{code="CONFIG_NOT_FOUND";constructor(t,r,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:i,searchPaths:r,searchPathCount:r.length})}},Qi=class extends et{code="CONFIG_LOAD_ERROR";constructor(t,r,i){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Mc=class extends et{code="CONFIG_VALIDATION_ERROR";constructor(t,r,i){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Ic=class extends et{code="CONFIG_MERGE_ERROR";constructor(t,r,i,n){super(`Failed to merge configuration from "${t}" with "${r}": ${i.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Rs=class extends et{code="ENV_VAR_ERROR";constructor(t,r,i,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${i}`,{envKey:t,envValue:r,expectedType:i,configName:n})}},_c=class extends et{code="FILE_SYSTEM_ERROR";constructor(t,r,i){super(`File system ${t} failed for "${r}": ${i.message}`,{operation:t,path:r,originalError:i.name,originalMessage:i.message});this.cause=i}},jc=class extends et{code="TYPE_GENERATION_ERROR";constructor(t,r,i){super(`Failed to generate types from "${t}" to "${r}": ${i.message}`,{configDir:t,outputPath:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Zi=class extends et{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Uc=class extends et{code="BROWSER_CONFIG_ERROR";constructor(t,r,i,n){super(`Failed to fetch configuration from "${t}": ${r} ${i}`,{endpoint:t,status:r,statusText:i,configName:n})}},Wc=class extends et{code="PLUGIN_ERROR";constructor(t,r,i){super(`Plugin "${t}" failed during ${r}: ${i.message}`,{pluginName:t,operation:r,originalError:i.name,originalMessage:i.message});this.cause=i}},lr={configNotFound(e,t,r){return new Ps(e,t,r)},configLoad(e,t,r){return new Qi(e,t,r)},configValidation(e,t,r){return new Mc(e,t,r)},configMerge(e,t,r,i){return new Ic(e,t,r,i)},envVar(e,t,r,i){return new Rs(e,t,r,i)},fileSystem(e,t,r){return new _c(e,t,r)},typeGeneration(e,t,r){return new jc(e,t,r)},schemaValidation(e,t,r){return new Zi(e,t,r)},browserConfig(e,t,r,i){return new Uc(e,t,r,i)},plugin(e,t,r){return new Wc(e,t,r)}},md={replace:"replace",concat:"concat",smart:"smart"},gd=/^https?:\/\//,vt=new Ts("bunfig",{showTags:!0}),_t=new Xc,pd=He(Ar.cwd(),"config"),yd=He(Ar.cwd(),"src/generated")});k$=xs.env.CLARITY_LOG_DIR||db(A$(),"logs"),wd={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:k$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},As={...wd},V1=(async()=>{try{let{loadConfig:e}=await R$().then(()=>td),t=await e({name:"clarity",alias:"logging",defaultConfig:wd,cwd:xs.cwd()});if(t)Object.assign(As,t)}catch{}return As})();Se={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},K=Se,Y1=Se.red,N$=Se.green,z1=Se.yellow,D$=Se.blue,G1=Se.magenta,q1=Se.cyan,qh=Se.white,J1=Se.gray,F$=Se.bgRed,B$=Se.bgYellow,X1=Se.bgGray,Jh=Se.bold,Q1=Se.dim,Z1=Se.italic,ek=Se.underline,tk=Se.strikethrough,rk=Se.reset,Ac={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},L$={debug:"\uD83D\uDD0D",info:D$("ℹ"),success:N$("✓"),warning:B$(qh(Jh(" WARN "))),error:F$(qh(Jh(" ERROR ")))};ik=new Bs("stacks");bt=class bt extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};bd=class bd extends bt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};ks=class ks extends bt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};$d=class $d extends bt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};xd=class xd extends bt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};Qc=class Qc extends bt{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};Cd=class Cd extends bt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Sd=class Sd extends bt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};Os=class Os extends bt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Ed=class Ed extends bt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};Td=class Td extends bt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};oi={configNotFound(e,t,r){return new bd(e,t,r)},configLoad(e,t,r){return new ks(e,t,r)},configValidation(e,t,r){return new $d(e,t,r)},configMerge(e,t,r,i){return new xd(e,t,r,i)},envVar(e,t,r,i){return new Qc(e,t,r,i)},fileSystem(e,t,r){return new Cd(e,t,r)},typeGeneration(e,t,r){return new Sd(e,t,r)},schemaValidation(e,t,r){return new Os(e,t,r)},browserConfig(e,t,r,i){return new Ed(e,t,r,i)},plugin(e,t,r){return new Td(e,t,r)}};H$=/^https?:\/\//;kt=new Bs("bunfig",{showTags:!0});Oc=new Nd;ck=lt(Ns.cwd(),"config"),lk=lt(Ns.cwd(),"src/generated")});import{homedir as el}from"node:os";import{join as tl,resolve as Y$}from"node:path";async function Ld(){if(!rl)rl=await Dd({name:"rpx",cwd:Y$(__dirname,".."),defaultConfig:Bd});return rl}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Bd,rl=null,jt;var Ls=Q(()=>{Fd();Bd={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:tl(el(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:tl(el(),".stacks","ssl","stacks.localhost.crt"),keyPath:tl(el(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};jt=Bd});function ai(e){return e.startsWith("*.")}function Or(e,t){if(!ai(t))return!1;let r=t.slice(1);return e.length>r.length&&e.endsWith(r)}function Md(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!ai(s))continue;if(Or(t,s)){let c=s.length-1;if(c>n)n=c,i=o}}return i}import{existsSync as z$,readdirSync as G$,readFileSync as q$,statSync as J$}from"node:fs";import{homedir as _d}from"node:os";import{isAbsolute as X$,join as ci}from"node:path";function nl(e,t){if(e==="~")return t;if(e.startsWith("~/"))return ci(t,e.slice(2));return e}function Z$(e){let t=e.indexOf(":");return(t===-1?e:e.slice(0,t)).toLowerCase()}function Ms(e){return e.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function ex(e,t){for(let r of t){let i=`.${r}`;if(e.endsWith(i)){let n=e.slice(0,-i.length);if(n.length>0&&!n.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(n))return n}}return null}function tx(e,t){let r=t.readText(ci(e,"rpx.site.json"));if(r)try{let n=JSON.parse(r);if(n&&typeof n==="object")return n}catch{}let i=t.readText(ci(e,"package.json"));if(i)try{let n=JSON.parse(i);if(n.rpx&&typeof n.rpx==="object")return n.rpx}catch{}return null}function rx(e){let t=e.selfRegisters??!1;return{command:e.command,env:e.env,urlEnv:e.urlEnv,selfRegisters:t,routes:e.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function ix(e,t){let r=tx(e,t);if(r?.command)return rx(r);let i=t.fileExists(ci(e,"buddy")),n=t.readText(ci(e,"package.json")),s=null;if(n)try{s=JSON.parse(n)}catch{s=null}let o={...s?.dependencies??{},...s?.devDependencies??{}};if(i||Object.keys(o).some((a)=>a==="stacks"||a.startsWith("@stacksjs/")))return{command:i?"./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(s?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function sl(e,t={}){let r={dirExists:t.dirExists??il.dirExists,fileExists:t.fileExists??il.fileExists,readText:t.readText??il.readText},i=t.detect??ix,n=t.homeDir??_d(),s=e.tlds??Ud,o=(e.roots??jd).map((h)=>nl(h,n)),c=e.idleTimeoutMs??Q$,a=new Map;for(let h of e.sites??[])a.set(h.to,h);let l=(h)=>h.idleTimeoutMs??c;function u(h){let d=Md(a,h);if(!d)return null;let y=X$(d.dir)?d.dir:nl(d.dir,n),g=d.selfRegisters??!1,p=d.routes??[];if(!g&&p.length===0)p=i(y,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let w=Id({...d.env??{}},void 0,h);return{host:h,id:Ms(h),dir:y,command:d.command,env:w,routes:p,selfRegisters:g,idleTimeoutMs:l(d),source:"config"}}function f(h){let d=ex(h,s);if(!d)return null;for(let y of o){let g=ci(y,d);if(!r.dirExists(g))continue;let p=i(g,r);if(!p)continue;let w=p.selfRegisters??!1;return{host:h,id:Ms(h),dir:g,command:p.command,env:Id({...p.env??{}},p.urlEnv,h),routes:w?[]:p.routes??[],selfRegisters:w,idleTimeoutMs:c,source:"discovered"}}return null}return{resolve(h){let d=Z$(h);if(!d)return null;return u(d)??f(d)}}}function nx(e){try{return G$(e,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function Wd(e,t={}){let r=t.homeDir??_d(),i=e.tlds??Ud,n=(e.roots??jd).map((f)=>nl(f,r)),s=t.readdir??nx,o=sl(e,t),c=[],a=new Set,l=(f)=>{if(f&&!a.has(f.host))a.add(f.host),c.push(f)};for(let f of e.sites??[])if(!f.to.includes("*"))l(o.resolve(f.to));let u=i[0]??"localhost";for(let f of n)for(let h of s(f))l(o.resolve(`${h}.${u}`));return c}function Id(e,t,r){if(!t)return e;let i=`https://${r}`;for(let n of t)if(e[n]===void 0)e[n]=i;return e}var jd,Ud,Q$=1800000,il;var ol=Q(()=>{jd=["~/Code"],Ud=["localhost","test"],il={dirExists:(e)=>{try{return J$(e).isDirectory()}catch{return!1}},fileExists:(e)=>{try{return z$(e)}catch{return!1}},readText:(e)=>{try{return q$(e,"utf8")}catch{return null}}}});var x;var Nr=Q(()=>{x={info:(...e)=>console.log("[info]",...e),success:(...e)=>console.log("[success]",...e),warn:(...e)=>console.warn("[warn]",...e),error:(...e)=>console.error("[error]",...e),debug:(...e)=>console.debug("[debug]",...e),log:(...e)=>console.log(...e),start:(...e)=>console.log("[start]",...e),box:(...e)=>console.log("[box]",...e)}});import{createRequire as sx}from"node:module";import{Resolver as al}from"node:dns/promises";import{createHash as ax,sign as cx}from"node:crypto";import{createHash as lx}from"node:crypto";import{sign as ux}from"node:crypto";import{generateKeyPairSync as Gm,X509Certificate as vx}from"node:crypto";import cl from"node:os";import ll from"node:path";import{existsSync as Hd,statSync as Vd}from"fs";import{existsSync as $x,mkdirSync as Nk,readdirSync as Dk,readFileSync as xx,writeFileSync as Fk}from"fs";import{homedir as li}from"os";import{dirname as Mk,resolve as dt}from"path";import Eo from"process";import{existsSync as Yd,statSync as zd}from"fs";import{existsSync as Dl,mkdirSync as Cx,readdirSync as Sx,writeFileSync as Ex}from"fs";import{homedir as ui}from"os";import{dirname as Gd,resolve as Ye}from"path";import Fr from"process";import{join as Tx,relative as Px,resolve as qd}from"path";import ao from"process";import{existsSync as qm,mkdirSync as zk,readdirSync as Gk,writeFileSync as qk}from"fs";import{homedir as ul}from"os";import{dirname as Qk,resolve as Ve}from"path";import on from"process";import{join as Rx,relative as Ax,resolve as Jd}from"path";import co from"process";import{existsSync as Jm,mkdirSync as iO,readdirSync as nO,writeFileSync as sO}from"fs";import{dirname as aO,resolve as lo}from"path";import Fl from"process";import{Buffer as ur}from"buffer";import{createCipheriv as kx,createDecipheriv as Ox,randomBytes as fl}from"crypto";import{closeSync as hl,createReadStream as Xd,createWriteStream as Nx,existsSync as dl,fsyncSync as Qd,openSync as Zd,writeFileSync as Dx}from"fs";import{access as Fx,constants as em,mkdir as Bx,readdir as Is,rename as tm,stat as fi,unlink as _s,writeFile as ml}from"fs/promises";import{join as hi}from"path";import Oe from"process";import{pipeline as Lx}from"stream/promises";import{createGzip as rm}from"zlib";import di from"process";import Ht from"process";import{Buffer as Ut}from"buffer";import{createCipheriv as Mx,createDecipheriv as Ix,randomBytes as gl}from"crypto";import{closeSync as pl,createReadStream as im,createWriteStream as _x,existsSync as js,fsyncSync as nm,openSync as sm,writeFileSync as jx}from"fs";import{access as Ux,constants as om,mkdir as Wx,readdir as Us,rename as am,stat as mi,unlink as Ws,writeFile as yl}from"fs/promises";import{isAbsolute as Kx,join as gi,resolve as Hx}from"path";import G from"process";import{pipeline as Vx}from"stream/promises";import{createGzip as cm}from"zlib";import pi from"process";import Vt from"process";import Ks from"process";import{existsSync as Hs}from"fs";import{resolve as wl}from"path";import{existsSync as Yx}from"fs";import{existsSync as zx,readdirSync as Gx}from"fs";import{extname as vl,resolve as lm}from"path";import qx from"process";import{join as Jx,relative as Xx,resolve as um}from"path";import uo from"process";import{Buffer as Wt}from"buffer";import{createCipheriv as Qx,createDecipheriv as Zx,randomBytes as bl}from"crypto";import{closeSync as $l,createReadStream as fm,createWriteStream as eC,existsSync as Vs,fsyncSync as hm,openSync as dm,writeFileSync as tC}from"fs";import{access as rC,constants as mm,mkdir as iC,readdir as Ys,rename as gm,stat as yi,unlink as zs,writeFile as xl}from"fs/promises";import{isAbsolute as nC,join as wi,resolve as sC}from"path";import q from"process";import{pipeline as oC}from"stream/promises";import{createGzip as pm}from"zlib";import vi from"process";import Yt from"process";import Gs from"process";import{existsSync as qs}from"fs";import{resolve as Cl}from"path";import{existsSync as aC}from"fs";import{exec as AS}from"node:child_process";import Vl from"node:fs";import kS from"node:os";import $t from"node:path";import Ng from"node:process";import{promisify as OS}from"node:util";import Ci from"node:crypto";import zt from"node:fs";import Gl from"node:path";import e0 from"node:crypto";import{execSync as i0}from"node:child_process";import Co from"node:os";async function Qs(e,t={},r=30000){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){if(i&&typeof i==="object"&&i.name==="TimeoutError"){let n=Error(`ACME HTTP request to ${e} timed out after ${r}ms`);throw n.name="AcmeRequestTimeoutError",n}throw i}}async function Bm(e,t,r={}){let i=r.timeoutMs??120000,n=r.intervalMs??3000,s=e.split(".").slice(-2).join("."),o;try{let l=new al,u=await l.resolveNs(s),f=(await Promise.all(u.map((h)=>l.resolve4(h).catch(()=>[])))).flat();if(f.length>0)o=new al,o.setServers(f)}catch{}let c=Date.now()+i,a=o??new al;for(;;){try{if((await a.resolveTxt(e)).some((l)=>l.join("")===t))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((l)=>setTimeout(l,n))}}class sn{tokens=new Map;add(e,t){this.tokens.set(e,t)}get(e){return this.tokens.get(e)}remove(e){this.tokens.delete(e)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(e){let t=e.indexOf(sn.PATH_PREFIX);if(t===-1)return;let r=e.slice(t+sn.PATH_PREFIX.length);return this.get(r)}}function Zs(e){return(typeof e==="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")}function Al(e){return Buffer.from(e,"base64url")}function Lm(e){let t=e.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Mm(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}","y":"${e.y}"}`;return ax("sha256").update(t).digest("base64url")}function Im(e){let{protectedHeader:t,payload:r,privateKey:i}=e,n=Zs(JSON.stringify(t)),s=r===""?"":Zs(JSON.stringify(r)),o=`${n}.${s}`,c=cx("sha256",Buffer.from(o),{key:i,dsaEncoding:"ieee-p1363"});return{protected:n,payload:s,signature:Zs(c)}}class oo{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(e){this.directoryUrl=e.directoryUrl,this.accountKey=e.accountKey,this.jwk=Lm(e.accountPublicKey),this.thumbprint=Mm(this.jwk),this.requestTimeoutMs=e.requestTimeoutMs??Fm}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let e=await Qs(this.directoryUrl,{},this.requestTimeoutMs);if(!e.ok)throw Error(`Failed to fetch ACME directory: HTTP ${e.status}`);return this.directoryCache=await e.json(),this.directoryCache}async newNonce(){let e=await this.directory(),t=(await Qs(e.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let e=this.nonce;return this.nonce=void 0,e}return this.newNonce()}async signedPost(e){let{url:t,payload:r,useJwk:i}=e,n={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(i)n.jwk=this.jwk;else n.kid=this.requireKid();let s=Im({protectedHeader:n,payload:r,privateKey:this.accountKey}),o=await Qs(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(s)},this.requestTimeoutMs),c=o.headers.get("replay-nonce");if(c)this.nonce=c;let a=o.headers.get("content-type")??"",l;if(a.includes("application/pem-certificate-chain")||a.startsWith("text/"))l=await o.text();else{let u=await o.text();l=u?JSON.parse(u):{}}if(o.status>=400){let u=l??{};throw new so(`ACME request to ${t} failed (HTTP ${o.status}): ${u.type??""} ${u.detail??""}`.trim(),u,o.status)}return{status:o.status,headers:o.headers,body:l,location:o.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(e={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(e.email)r.contact=[`mailto:${e.email}`];let i=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!i.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=i.location,this.accountKid}async newOrder(e){let t=await this.directory(),r={identifiers:e.map((n)=>({type:"dns",value:n}))},i=await this.signedPost({url:t.newOrder,payload:r});if(!i.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:i.body,orderUrl:i.location}}async getAuthorization(e){return(await this.signedPost({url:e,payload:""})).body}keyAuthorization(e){return`${e}.${this.thumbprint}`}dns01TxtValue(e){return lx("sha256").update(this.keyAuthorization(e)).digest("base64url")}async notifyChallengeReady(e){await this.signedPost({url:e,payload:{}})}async pollAuthorization(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getAuthorization(e);if(s.status==="valid")return;if(s.status==="invalid"){let o=s.challenges.find((c)=>c.status==="invalid");throw new so(`Authorization for ${s.identifier.value} became invalid: ${o?.error?.detail??"unknown reason"}`,o?.error??{},0)}await Kd(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for authorization ${e} to become valid`)}async finalizeOrder(e,t){return(await this.signedPost({url:e,payload:{csr:t}})).body}async getOrder(e){return(await this.signedPost({url:e,payload:""})).body}async pollOrder(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getOrder(e);if(s.status==="valid"){if(!s.certificate)throw Error("ACME order is valid but has no certificate URL");return s.certificate}if(s.status==="invalid")throw Error(`ACME order ${e} became invalid`);await Kd(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for order ${e} to become valid`)}async downloadCertificate(e){let t=await this.signedPost({url:e,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(e,t){let r=e.challenges.find((i)=>i.type===t);if(!r)throw Error(`No ${t} challenge available for ${e.identifier.value}`);return r}}function Um(e){let t=e.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${e.trim()}
|
|
62
|
+
`,chainPem:""};let i=`${r.trim()}
|
|
63
|
+
`,n=t.slice(1).map((s)=>s.trim()).join(`
|
|
64
|
+
`);return{certPem:i,chainPem:n?`${n}
|
|
65
|
+
`:""}}function Wm(e){return`_acme-challenge.${e.startsWith("*.")?e.slice(2):e}`}function Kd(e){return new Promise((t)=>setTimeout(t,e))}function fx(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function dr(e,t){return Buffer.concat([Buffer.from([e]),fx(t.length),t])}function Km(e){let t;if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=[],i=e;while(i>0)r.unshift(i&255),i>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=e.length===0?Buffer.from([0]):e,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return dr(2,t)}function Dr(e){let t=e.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${e}`);let r=[40*t[0]+t[1]];for(let i=2;i<t.length;i++){let n=t[i],s=[n&127];n=Math.floor(n/128);while(n>0)s.unshift(n&127|128),n=Math.floor(n/128);r.push(...s)}return dr(6,Buffer.from(r))}function ht(...e){return dr(48,Buffer.concat(e))}function kl(...e){return dr(49,Buffer.concat(e))}function Ol(e){return dr(3,Buffer.concat([Buffer.from([0]),e]))}function Hm(e){return dr(4,e)}function Vm(e){return dr(12,Buffer.from(e,"utf8"))}function Nl(e,t,r){let i=128|(r?32:0)|e;return dr(i,t)}function wx(e){let t=e.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Al(t.x),i=Al(t.y);if(r.length!==32||i.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${i.length}`);return Buffer.concat([Buffer.from([4]),r,i])}function Ym(e){let{domains:t,publicKey:r,privateKey:i}=e;if(t.length===0)throw Error("At least one domain is required to build a CSR");let n=ht(kl(ht(Dr(gx),Vm(t[0])))),s=ht(ht(Dr(hx),Dr(dx)),Ol(wx(r))),o=t.map((g)=>Nl(2,Buffer.from(g,"ascii"),!1)),c=ht(...o),a=ht(Dr(yx),Hm(c)),l=ht(a),u=ht(Dr(px),kl(l)),f=Nl(0,u,!0),h=ht(Km(0),n,s,f),d=ux("sha256",h,i),y=ht(Dr(mx));return ht(h,y,Ol(d))}function zm(e){return Ym(e).toString("base64url")}function bx(e){if(e){let{createPrivateKey:n,createPublicKey:s}=ox("node:crypto"),o=n(e),c=s(o.export({format:"pem",type:"pkcs8"}));return{privateKey:o,publicKey:c,pem:e}}let{privateKey:t,publicKey:r}=Gm("ec",{namedCurve:"P-256"}),i=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:i}}async function ql(e){let{domains:t,method:r}=e;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!e.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((f)=>f.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let i=e.directoryUrl??(e.staging===!1?jm:_m),n=bx(e.accountKeyPem),s=new oo({directoryUrl:i,accountKey:n.privateKey,accountPublicKey:n.publicKey,requestTimeoutMs:e.requestTimeoutMs});await s.newAccount({email:e.email});let{order:o,orderUrl:c}=await s.newOrder(t),a=e.http01Store??So,l=[],u=[];try{for(let v of o.authorizations){let T=await s.getAuthorization(v);if(T.status==="valid")continue;let S=oo.selectChallenge(T,r);if(r==="dns-01"){let D=Wm(T.identifier.value),W=s.dns01TxtValue(S.token);await e.dnsProvider.setTxt(D,W),l.push({name:D,value:W}),await Bm(D,W,{timeoutMs:e.dnsPropagationTimeoutMs??120000})}else a.add(S.token,s.keyAuthorization(S.token)),u.push(S.token);await s.notifyChallengeReady(S.url),await s.pollAuthorization(v,{timeoutMs:e.timeoutMs})}let{privateKey:f,publicKey:h}=Gm("ec",{namedCurve:"P-256"}),d=zm({domains:t,publicKey:h,privateKey:f});await s.finalizeOrder(o.finalize,d);let y=await s.pollOrder(c,{timeoutMs:e.timeoutMs}),g=await s.downloadCertificate(y),{certPem:p,chainPem:w}=Um(g),b=w?`${p}${w}`:p,P=f.export({format:"pem",type:"pkcs8"}).toString(),R=new Date(new vx(p).validTo);return{certPem:p,keyPem:P,chainPem:w,fullChainPem:b,accountKeyPem:n.pem,notAfter:R}}finally{for(let{name:f,value:h}of l)await e.dnsProvider?.removeTxt(f,h).catch(()=>{});for(let f of u)a.remove(f)}}class Xm{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Hd(e))return!0;return Vd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Hd(r)?Vd(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Qm{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function uC(e,t){this[e]=lC.bind(null,t)}class Xl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Yd(e))return!0;return zd(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Yd(r)?zd(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Ql{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function dC(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function mC(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function gC(e){return e.getStats().size*2}function Zl(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&ne(t[0])&&"id"in t[0]&&t[0].id===3&&ne(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(ne(t)&&ne(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(ne(e)&&"arr"in e&&Array.isArray(e.arr)&&ne(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&ne(t[0])&&ne(e[0])){let i=[...t];for(let n of e)if(ne(n)&&"name"in n){if(!i.find((s)=>ne(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(ne(n)&&"path"in n){if(!i.find((s)=>ne(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>ho(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!ne(t)||!ne(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(ne(n)&&ne(r[i]))r[i]=Zl(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&ne(n[0])&&ne(r[i][0])){let s=[...n];for(let o of r[i])if(ne(o)&&"name"in o){if(!s.find((c)=>ne(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(ne(o)&&"path"in o){if(!s.find((c)=>ne(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>ho(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function ho(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ho(e[r],t[r]))return!1;return!0}if(ne(e)&&ne(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ho(e[n],t[n]))return!1}return!0}return!1}function ne(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function pC(e,t){if(!Jm(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return Zl(t,i)}catch{return null}}catch{return null}}async function yC({name:e="",cwd:t,defaultConfig:r}){let i=t||Fl.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of n){let a=lo(i,`${o}${c}`),l=await pC(a,r);if(l!==null)return l}try{let o=lo(i,"package.json");if(Jm(o)){let c=(await import(o))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Zl(r,c)}catch{}}}catch{}return r}function wC(e,t={}){let r=co.cwd();while(r.includes("storage"))r=Jd(r,"..");let i=Jd(r,e||"");if(t?.relative)return Ax(co.cwd(),i);return i}async function vC(){try{let e=await yC({name:"clarity",defaultConfig:to,cwd:co.cwd(),endpoint:"",headers:{}});return{...to,...e}}catch{return to}}function ce(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bC(){if(Ht.env.NODE_ENV==="test"||Ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Ht<"u"){let e=Ht.type;if(e==="renderer"||e==="worker")return!1;return!!(Ht.versions&&(Ht.versions.node||Ht.versions.bun))}return!1}class eg{async format(e){let t=await bC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:di.pid,hostname:t(),environment:di.env.NODE_ENV||"development",platform:di.platform,version:di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:di.env.NODE_ENV||di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mo{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(e,t={}){this.name=e,this.config={...Ll},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new eg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Oe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...ro,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...ro};return{...ro,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ll.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Fx(this.config.logDirectory,em.F_OK|em.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Bx(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ur.from(e);try{if(!dl(this.currentLogFile))await ml(this.currentLogFile,"",{mode:420});if(i=Zd(this.currentLogFile,"a",420),Dx(i,c,{flag:"a"}),Qd(i),i!==void 0)hl(i),i=void 0;if((await fi(this.currentLogFile)).size===0){if(await ml(this.currentLogFile,c,{flag:"w",mode:420}),(await fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=o*2**n;await new Promise((h)=>setTimeout(h,f)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{hl(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(n===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let a=o*2**(n-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 hi(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 hi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return hi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ce())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return fl(16).toString("hex")}generateKey(){return fl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=fl(16),i=kx("aes-256-gcm",t,r),n=ur.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:ur.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=rm(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ur.from(ur.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ce())return;let e=await fi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Is(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await fi(r).catch(()=>null))try{if(await tm(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await _s(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await ml(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await fi(r).catch(()=>null))await tm(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Is(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await _s(hi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Xd(e),i=Nx(t),n=rm();await Lx(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),dl(this.currentLogFile))try{let e=Zd(this.currentLogFile,"r+");Qd(e),hl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Is(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await _s(hi(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?ee.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=Oe.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${ee.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!ce()){let l=ug[e],u=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:ee.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:ee.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
66
|
+
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:ee.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!ce()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
67
|
+
`;if(c)a+=`${c}
|
|
68
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!ce()){let r=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:ee.blue("◐"),tag:r,message:`${ee.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
69
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.fancy&&!ce()){let l=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:ee.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ce())console.error(a.trim());await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new mo(t,{...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(r),r}createReadStream(){if(ce())throw Error("createReadStream is not supported in browser environments");if(!dl(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xd(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=ur.isBuffer(e)?e:ur.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),c=Ox("aes-256-gcm",r,n);return c.setAuthTag(s),ur.concat([c.update(o),c.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ce()}isServerMode(){return!ce()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!ce()){let s=e.split(`
|
|
70
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:ee.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:ee.cyan(a),showTimestamp:!1}))}else if(!ce())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
|
|
71
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(ce())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${ee.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();Oe.stdin.removeListener("data",r);try{if(typeof Oe.stdin.setRawMode==="function")Oe.stdin.setRawMode(!1)}catch{}Oe.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Oe.stdin.setRawMode==="function")Oe.stdin.setRawMode(!0)}catch{}Oe.stdin.resume(),Oe.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let n=/%([sdijfo%])/g,s=0;if(r=e.replace(n,(o,c)=>{if(c==="%")return"%";if(s>=t.length)return o;let a=t[s++];switch(c){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!ce()){let n=this.options.showTags!==!1&&this.name?ee.gray(this.formatTag(this.name)):"",s=ee.blue("◐");console.error(`${s} ${n} ${ee.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
72
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||ce()||e<=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 r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(i,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ce())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),n!==void 0)this.activeProgressBar.message=n;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ce())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||ce())return;Oe.stdout.write(`${"\r".padEnd(Oe.stdout.columns||80)}\r`),this.log(n,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||ce()||!Oe.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=ee.green("━".repeat(i)),o=ee.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?ee.green("✓"):ee.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${ee.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Oe.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Oe.stdout.write(e.lastRenderedLine),t)Oe.stdout.write(`
|
|
73
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ce()||!Oe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Is(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=hi(this.config.logDirectory,i);if(e.before)try{if((await fi(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await _s(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function eo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&J(t[0])&&"id"in t[0]&&t[0].id===3&&J(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(J(t)&&J(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(J(e)&&"arr"in e&&Array.isArray(e.arr)&&J(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&J(t[0])&&J(e[0])){let i=[...t];for(let n of e)if(J(n)&&"name"in n){if(!i.find((s)=>J(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(J(n)&&"path"in n){if(!i.find((s)=>J(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>go(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!J(t)||!J(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(J(n)&&J(r[i]))r[i]=eo(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&J(n[0])&&J(r[i][0])){let s=[...n];for(let o of r[i])if(J(o)&&"name"in o){if(!s.find((c)=>J(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(J(o)&&"path"in o){if(!s.find((c)=>J(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((c)=>go(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function eu(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:eo(e,t);if(Array.isArray(e))return r==="replace"?t:eo(e,t);if(!J(t)||!J(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=eo(o,s);else if(J(s)&&J(o))i[n]=eu(o,s,r);else i[n]=s}return i}function go(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!go(e[r],t[r]))return!1;return!0}if(J(e)&&J(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!go(e[n],t[n]))return!1}return!0}return!1}function J(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Js(e,t,r="replace"){if(!qm(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return eu(t,n,r)}catch{return null}}catch{return null}}function $C(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,y=`${i}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)De.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=on.env[d]||on.env[y];if(g!==void 0){if(r)De.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(n)}async function xC({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?$C(e,n,s):n,l=r||on.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)De.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ve(l,"config"),Ve(l,".config"),i?Ve(l,i):void 0].filter(Boolean)));for(let p of g){if(s)De.info(`Searching for configuration in: ${p}`);let w=[Ve(l,"config"),Ve(l,".config")].concat(i?[Ve(l,i)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from: ${R}`);return v}}}if(e){let p=Ve(ul(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)De.info(`Checking user config directory: ${p}`);for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from user config directory: ${R}`);return v}}}if(e){let p=Ve(ul(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)De.info(`Checking user config directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from user config directory dotfile: ${R}`);return v}}}if(e){let p=ul(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)De.info(`Checking user home directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ve(p,`${b}${P}`),v=await Js(R,a,c);if(v!==null){if(s)De.success(`Configuration loaded from user home directory: ${R}`);return v}}}try{let p=Ve(l,"package.json");if(qm(p)){let w=await import(p),b=w[e];if(!b&&t){if(b=w[t],b&&s)De.success(`Using alias "${t}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(s)De.success(`Configuration loaded from package.json: ${b===w[e]?e:t}`);return eu(a,b,c)}catch(P){if(s)De.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)De.warn("Failed to load package.json:",p)}if(s)De.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function CC(e,t={}){let r=ao.cwd();while(r.includes("storage"))r=qd(r,"..");let i=qd(r,e||"");if(t?.relative)return Px(ao.cwd(),i);return i}async function SC(){try{let e=await xC({name:"clarity",alias:"logging",defaultConfig:io,cwd:ao.cwd()});return{...io,...e||{}}}catch{return io}}function we(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EC(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let e=Vt.type;if(e==="renderer"||e==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class tg{async format(e){let t=await EC(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:pi.pid,hostname:t(),environment:pi.env.NODE_ENV||"development",platform:pi.platform,version:pi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pi.env.NODE_ENV||pi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class po{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(e,t={}){this.name=e,this.config={...Ml},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new tg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??G.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...no,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...no};return{...no,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ml.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!we()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Ux(this.config.logDirectory,om.F_OK|om.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await Wx(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Ut.from(e);try{if(!js(this.currentLogFile))await yl(this.currentLogFile,"",{mode:420});if(i=sm(this.currentLogFile,"a",420),jx(i,c,{flag:"a"}),nm(i),i!==void 0)pl(i),i=void 0;if((await mi(this.currentLogFile)).size===0){if(await yl(this.currentLogFile,c,{flag:"w",mode:420}),(await mi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=o*2**n;await new Promise((h)=>setTimeout(h,f)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{pl(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(n===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let a=o*2**(n-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 gi(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 gi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return gi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(we())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return gl(16).toString("hex")}generateKey(){return gl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=gl(16),i=Mx("aes-256-gcm",t,r),n=Ut.isBuffer(e)?e:Ut.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Ut.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=cm(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Ut.from(Ut.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(we())return;if(!this.shouldWriteToFile())return;let e=await mi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Us(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await mi(r).catch(()=>null))try{if(await am(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ws(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await yl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await mi(r).catch(()=>null))await am(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Us(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ws(gi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=im(e),i=_x(t),n=cm();await Vx(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),js(this.currentLogFile))try{let e=sm(this.currentLogFile,"r+");nm(e),pl(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!we()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Us(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ws(gi(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?j.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||we())return!1;let e=typeof G.env.NO_COLOR<"u",t=G.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof G.stderr<"u"&&G.stderr.isTTY||typeof G.stdout<"u"&&G.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=G.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${j.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=j.underline(j.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>j.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>j.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>j.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>j.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>j.strikethrough(i)),t}supportsHyperlinks(){if(we())return!1;let e=G.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=G.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Kx(t)||t.startsWith("./")||t.startsWith("../"))t=Hx(t);else return null;return js(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":fg[e],h=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:j.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:j.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
74
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:j.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!we()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
75
|
+
`;if(c)u+=`${c}
|
|
76
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!we()&&G.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!we()&&G.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!we()&&G.stdout.isTTY)G.stdout.write(`
|
|
77
|
+
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!we()&&G.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:r,message:`${j.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
78
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":j.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!we())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new po(t,{...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(r),r}createReadStream(){if(we())throw Error("createReadStream is not supported in browser environments");if(!js(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return im(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Ut.isBuffer(e)?e:Ut.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),c=Ix("aes-256-gcm",r,n);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Ut.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return we()}isServerMode(){return!we()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
79
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:j.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:j.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:j.cyan(u),showTimestamp:!1}))}else if(!we())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
80
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(we())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${j.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();G.stdin.removeListener("data",r);try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!1)}catch{}G.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof G.stdin.setRawMode==="function")G.stdin.setRawMode(!0)}catch{}G.stdin.resume(),G.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${c}${o} ${j.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
81
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!G.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=j.green("━".repeat(i)),o=j.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?j.green("✓"):j.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=G.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,G.stdout.write(e.lastRenderedLine),t)G.stdout.write(`
|
|
82
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||we()||!G.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(we()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Us(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=gi(this.config.logDirectory,i);if(e.before)try{if((await mi(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Ws(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function rg(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function ig(e){return e instanceof tt}function TC(e){return e instanceof yo}function PC(e){if(ig(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class To{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return un.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),a=`${r}_${c.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=Ks.env[a]||(l?Ks.env[l]:void 0);if(u!==void 0){if(i.verbose){let f=Ks.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof s,a,i.customParsers,i.configName)}catch(f){if(f instanceof wo)throw f;throw hr.envVar(a,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw hr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Ks.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
83
83
|
|
|
84
|
-
`;for(let
|
|
85
|
-
`,
|
|
86
|
-
`,
|
|
87
|
-
`,
|
|
84
|
+
`;for(let i of e)r+=`${i.key}
|
|
85
|
+
`,r+=` Type: ${i.type}
|
|
86
|
+
`,r+=` Description: ${i.description}
|
|
87
|
+
`,r+=` Example: ${i.example}
|
|
88
88
|
|
|
89
|
-
`;return
|
|
89
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
90
90
|
|
|
91
|
-
`;
|
|
92
|
-
`,
|
|
93
|
-
`;for(let
|
|
94
|
-
`;return Y}}function gE(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 zB(w,$,Y,new WeakMap)}function zB(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 fB(w,$,X,A);if(!Gw($)||!Gw(w))return $;return pE(w,$,Y,A)}function fB(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 dE(w,$);case"smart":return nE(w,$,A);default:return $}return $}function dE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>bU(X,A)))Y.push(A);return Y}function nE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Gw($[0])&&Gw(w[0]))return lE(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 lE(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((W)=>Gw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function pE(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]=zB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=fB(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(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(!bU(w[X],$[X]))return!1}return!0}return!1}function Gw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class OX{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=R1.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()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new UY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new UY(w,Error("Configuration must export a valid object"),"unknown");let T={config:XW($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)R1.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 z=[],f=[],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 z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await QY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!WE($))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 OX;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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(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||z))throw W;if(f&&(!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)Rw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Rw.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:z=!1}=w,f=J||k$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(n0(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw B$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?YY(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Rw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Rw.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=[n0(z1(),".config",w),n0(z1(),".config"),z1()];for(let W of j){if(X)Rw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Rw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?YY(w,A,J):A;try{let W=n0(Y,"package.json");if(!PU(W))return null;let Q=await import(W),z=Q[w],f=w;if(!z&&$)z=Q[$],f=$;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Rw.success(`Configuration loaded from package.json: ${f}`);return{config:XW(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Rw.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 R1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);R1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,n0(w,"config"),n0(w,".config"),$?n0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(n0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[n0(z1(),".config",w),n0(z1(),".config"),z1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Rf(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 rE(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)Rw.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 tE(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"&&Rf(Y)))return(await rw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await rw.loadConfig({...w,cwd:w.cwd||k$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Rf($)))return(await rw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function aE(w,$,Y="replace"){let A=new OX;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,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=k$.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function sE(w){let $=n0(k$.cwd(),w.configDir),Y=n0(k$.cwd(),w.generatedDir),A=n0(Y,"config-types.ts");if(!PU(oz(A)))bF(oz(A),{recursive:!0,mode:511});let X=PU($)?uF($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${VT}
|
|
95
|
-
export type ConfigNames = ${
|
|
96
|
-
`;
|
|
97
|
-
${
|
|
91
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
92
|
+
`,r+=`|----------|------|-------------|----------|
|
|
93
|
+
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
94
|
+
`;return r}}function RC(e,t){let r=cg("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function ng(e,t,r={}){return sg(e,t,r,new WeakMap)}function sg(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return og(e,t,n,i);if(!mt(t)||!mt(e))return t;return NC(e,t,r,i)}function og(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return AC(e,t);case"smart":return kC(e,t,i);default:return t}return t}function AC(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Bl(n,i)))r.push(i);return r}function kC(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(mt(t[0])&&mt(e[0]))return OC(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function OC(e,t,r){let i=[...t];for(let n of e){if(!mt(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((a)=>mt(a)&&(c in a)&&a[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function NC(e,t,r,i){let n=t;if(mt(n)&&i.has(n))return i.get(n);let s={...e};if(mt(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(mt(c)&&mt(a))s[o]=sg(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=og(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function tu(e,t,r="replace"){return ng(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Bl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Bl(e[r],t[r]))return!1;return!0}if(mt(e)&&mt(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Bl(e[n],t[n]))return!1}return!0}return!1}function mt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Po{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=$i.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!Hs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new an(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new an(e,Error("Configuration must export a valid object"),"unknown");let y={config:tu(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)$i.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?hr.configLoad(e,l):hr.configLoad(e,Error(String(l)))}};if(o)return un.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(wl(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return rg(async()=>Hs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Hs(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=wl(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=wl(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!Hs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class ru{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await un.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Yx(t))throw new cn(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new cn(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:dg},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class iu{fileLoader=new Po;envProcessor=new To;validator=new ru;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)xt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw xt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Fr.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(Ye(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw hr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?rn(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)xt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)xt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?rn(e,r,n):r,c=[Ye(ui(),".config",e),Ye(ui(),".config"),ui()];for(let a of c){if(n)xt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)xt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?rn(e,i,s):i;try{let a=Ye(r,"package.json");if(!Dl(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)xt.success(`Configuration loaded from package.json: ${f}`);return{config:tu(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)xt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:rn(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw hr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return $i.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);$i.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,Ye(e,"config"),Ye(e,".config"),t?Ye(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Ye(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Ye(ui(),".config",e),Ye(ui(),".config"),ui()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function ym(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function DC(e){return Gt.loadConfig({...e,__strictErrorHandling:!0})}async function ag(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await Gt.loadConfig(e);else i=await Gt.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)xt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Gt.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function FC(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Gt.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ym(r)))return(await Gt.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Gt.loadConfig({...e,cwd:e.cwd||Fr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ym(t)))return(await Gt.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function BC(e,t,r="replace"){let i=new Po;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function rn(e,t,r=!1){let i=new To,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Fr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function LC(e){let t=Ye(Fr.cwd(),e.configDir),r=Ye(Fr.cwd(),e.generatedDir),i=Ye(r,"config-types.ts");if(!Dl(Gd(i)))Cx(Gd(i),{recursive:!0,mode:511});let n=Dl(t)?Sx(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${fS}
|
|
95
|
+
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
96
|
+
`;Ex(i,s,{mode:438})}function MC(e){let t=null,r=null,i=()=>{if(!r)r=ag(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)xt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let c=n[o];return i(),c},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,c){if(!t)t={...n};return t[o]=c,!0}})}function IC(e){let t=lm(qx.cwd(),e?.configDir||"./config");function r(){if(!zx(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Gx(t).filter((a)=>n.has(vl(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=vl(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=vl(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((a)=>a.base),o=s.length?s.map((a)=>`'${a}'`).join(" | "):"string",c=n.length?`{
|
|
97
|
+
${n.map((a)=>{let l=lm(t,a.file).replace(/\\/g,"/");return` '${a.base}': typeof import('${l}').default`}).join(`,
|
|
98
98
|
`)}
|
|
99
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
100
|
-
export type ConfigByName = ${
|
|
99
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
100
|
+
export type ConfigByName = ${c}
|
|
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 OT(w,$={}){let Y=BX.cwd();while(Y.includes("storage"))Y=Kf(Y,"..");let A=Kf(Y,w||"");if($?.relative)return BE(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 _T(){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 _T(),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 SX{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{...hU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...hU};return{...hU,...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 TE(this.config.logDirectory,Nf.F_OK|Nf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await NE(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=Tf(this.currentLogFile,"a",420),EE(A,j,{flag:"a"}),Ef(A),A!==void 0)yU(A),A=void 0;if((await T1(this.currentLogFile)).size===0){if(await CU(this.currentLogFile,j,{flag:"w",mode:420}),(await T1(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 z=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let f=U*2**X;await new Promise((B)=>setTimeout(B,f)),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{yU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,z=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),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 N1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return N1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(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 IU(16).toString("hex")}generateKey(){return IU(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=IU(16),A=GE("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=Hf(),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 T1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await T1(Y).catch(()=>null))try{if(await qf(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 T1(Y).catch(()=>null))await qf(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(N1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Ff(w),A=FE($),X=Hf();await RE(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=Tf(this.currentLogFile,"r+");Ef(w),yU(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(N1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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(qE($)||$.startsWith("./")||$.startsWith("../"))$=HE($);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 f=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:f,tag:B,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
104
|
-
`);for(let
|
|
105
|
-
`;if(
|
|
106
|
-
`;if(
|
|
107
|
-
`);if(this[
|
|
108
|
-
`,
|
|
109
|
-
`),
|
|
110
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
111
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
112
|
-
`)}finishProgressBar(
|
|
103
|
+
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}function dS(e,t={}){let r=uo.cwd();while(r.includes("storage"))r=um(r,"..");let i=um(r,e||"");if(t?.relative)return Xx(uo.cwd(),i);return i}function be(){if(Yt.env.NODE_ENV==="test"||Yt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function gS(){if(Yt.env.NODE_ENV==="test"||Yt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Yt<"u"){let e=Yt.type;if(e==="renderer"||e==="worker")return!1;return!!(Yt.versions&&(Yt.versions.node||Yt.versions.bun))}return!1}class yg{async format(e){let t=await gS(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:vi.pid,hostname:t(),environment:vi.env.NODE_ENV||"development",platform:vi.platform,version:vi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vi.env.NODE_ENV||vi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ro{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(e,t={}){this.name=e,this.config={...vo},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new yg,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Rl,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Rl};return{...Rl,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:vo.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!be()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await rC(this.config.logDirectory,mm.F_OK|mm.W_OK)}catch(a){if(a instanceof Error&&"code"in a)if(a.code==="ENOENT")await iC(this.config.logDirectory,{recursive:!0,mode:493});else if(a.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw a;else throw a}}catch(a){throw console.error("Debug: [writeToFile] Failed to create log directory:",a),a}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Wt.from(e);try{if(!Vs(this.currentLogFile))await xl(this.currentLogFile,"",{mode:420});if(i=dm(this.currentLogFile,"a",420),tC(i,c,{flag:"a"}),hm(i),i!==void 0)$l(i),i=void 0;if((await yi(this.currentLogFile)).size===0){if(await xl(this.currentLogFile,c,{flag:"w",mode:420}),(await yi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(a){let l=a;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let u=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,u);let f=o*2**n;await new Promise((h)=>setTimeout(h,f)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{$l(i)}catch(a){console.error("Debug: [writeToFile] Error closing file descriptor:",a)}}}catch(c){if(n===s-1){let l=c,u=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}n++;let a=o*2**(n-1);await new Promise((l)=>setTimeout(l,a))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}finally{this.pendingOperations.splice(r,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 wi(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 wi(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return wi(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(be())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,c])=>c.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return bl(16).toString("hex")}generateKey(){return bl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=bl(16),i=Qx("aes-256-gcm",t,r),n=Wt.isBuffer(e)?e:Wt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Wt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=pm(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Wt.from(Wt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(be())return;if(!this.shouldWriteToFile())return;let e=await yi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ys(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await yi(r).catch(()=>null))try{if(await gm(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await zs(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await xl(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await yi(r).catch(()=>null))await gm(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ys(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await zs(wi(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=fm(e),i=eC(t),n=pm();await oC(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Vs(this.currentLogFile))try{let e=dm(this.currentLogFile,"r+");hm(e),$l(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!be()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ys(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await zs(wi(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?H.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||be())return!1;let e=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=q.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${H.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=H.underline(H.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>H.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>H.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>H.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>H.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>H.strikethrough(i)),t}supportsHyperlinks(){if(be())return!1;let e=q.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=q.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(nC(t)||t.startsWith("./")||t.startsWith("../"))t=sC(t);else return null;return Vs(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":bS[e],h=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:H.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:H.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
104
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:H.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!be()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
105
|
+
`;if(c)u+=`${c}
|
|
106
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!be()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!be()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!be()&&q.stdout.isTTY)q.stdout.write(`
|
|
107
|
+
`);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!be()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":H.blue("◐"),tag:r,message:`${H.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),a=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)a+=` ${JSON.stringify(r)}`;if(a+=`
|
|
108
|
+
`,a=a.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":H.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!be())console.error(a.trim());if(this.shouldWriteToFile())await this.writeToFile(a)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Ro(t,{...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(r),r}createReadStream(){if(be())throw Error("createReadStream is not supported in browser environments");if(!Vs(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fm(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Wt.isBuffer(e)?e:Wt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),c=Zx("aes-256-gcm",r,n);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Wt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return be()}isServerMode(){return!be()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
109
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:H.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:H.cyan(u),showTimestamp:!1}))}else if(!be())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
110
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(be())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${H.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();q.stdin.removeListener("data",r);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?H.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${H.blue("◐")} `;console.error(`${c}${o} ${H.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
111
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=H.green("━".repeat(i)),o=H.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?H.green("✓"):H.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${H.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=q.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,q.stdout.write(e.lastRenderedLine),t)q.stdout.write(`
|
|
112
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||be()||!q.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(be()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ys(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=wi(this.config.logDirectory,i);if(e.before)try{if((await yi(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await zs(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function $S(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class su{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return Jl.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),a=`${r}_${c.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=Gs.env[a]||(l?Gs.env[l]:void 0);if(u!==void 0){if(i.verbose){let f=Gs.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof s,a,i.customParsers,i.configName)}catch(f){if(f instanceof nu)throw f;throw xi.envVar(a,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw xi.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Gs.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
113
113
|
|
|
114
|
-
`;for(let
|
|
115
|
-
`,
|
|
116
|
-
`,
|
|
117
|
-
`,
|
|
114
|
+
`;for(let i of e)r+=`${i.key}
|
|
115
|
+
`,r+=` Type: ${i.type}
|
|
116
|
+
`,r+=` Description: ${i.description}
|
|
117
|
+
`,r+=` Example: ${i.example}
|
|
118
118
|
|
|
119
|
-
`;return
|
|
119
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
120
120
|
|
|
121
|
-
`;
|
|
122
|
-
`,
|
|
123
|
-
`;for(let
|
|
124
|
-
`;return Y}}function iT(w,$,Y={}){return _B(w,$,Y,new WeakMap)}function _B(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 hB(w,$,X,A);if(!Kw($)||!Kw(w))return $;return cT(w,$,Y,A)}function hB(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(Kw($[0])&&Kw(w[0]))return vT(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 vT(w,$,Y){let A=[...$];for(let X of w){if(!Kw(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)=>Kw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function cT(w,$,Y,A){let X=$;if(Kw(X)&&A.has(X))return A.get(X);let J={...w};if(Kw(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(Kw(j)&&Kw(W))J[U]=_B(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=hB(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(Kw(w)&&Kw($)){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 Kw(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()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new RX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new RX(w,Error("Configuration must export a valid object"),"unknown");let T={config:DB($,f,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?M1.configLoad(w,Q):M1.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 z=[],f=[],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 z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await eU.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!ME($))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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(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||z))throw W;if(f&&(!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:z=!1}=w,f=J||VX.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(Bw(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw M1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),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,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)gw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),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=[Bw(Q1(),".config",w),Bw(Q1(),".config"),Q1()];for(let W of j){if(X)gw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)gw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?eA(w,A,J):A;try{let W=Bw(Y,"package.json");if(!PF(W))return null;let Q={};try{Q=JSON.parse(iF(W,"utf8"))}catch(B){if(J)gw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let z=Q[w],f=w;if(!z&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){z=Q[G],f=G;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)gw.success(`Configuration loaded from package.json: ${f}`);return{config:DB(j,z,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 M1.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,Bw(w,"config"),Bw(w,".config"),$?Bw(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(Bw(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=[Bw(Q1(),".config",w),Bw(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 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,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=VX.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}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=Hw.join(X,U);try{if(rU.statSync(j).isDirectory())A(j);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function O(w,$,Y){if(Y||z0.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 IX(w){if(Array.isArray(w))return w.map((Y)=>IX(Y));if(typeof w==="string")return tT.test(w)?kf:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(aT(Y)){$[Y]=kf;continue}$[Y]=IX(A)}return $}function _X(w){return JSON.stringify(IX(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 f$(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: ${
|
|
126
|
-
${
|
|
121
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
122
|
+
`,r+=`|----------|------|-------------|----------|
|
|
123
|
+
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
124
|
+
`;return r}}function xS(e,t,r={}){return Eg(e,t,r,new WeakMap)}function Eg(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return Tg(e,t,n,i);if(!gt(t)||!gt(e))return t;return TS(e,t,r,i)}function Tg(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return CS(e,t);case"smart":return SS(e,t,i);default:return t}return t}function CS(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Hl(n,i)))r.push(i);return r}function SS(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(gt(t[0])&>(e[0]))return ES(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function ES(e,t,r){let i=[...t];for(let n of e){if(!gt(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((a)=>gt(a)&&(c in a)&&a[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function TS(e,t,r,i){let n=t;if(gt(n)&&i.has(n))return i.get(n);let s={...e};if(gt(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(gt(c)&>(a))s[o]=Eg(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=Tg(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function Pg(e,t,r="replace"){return xS(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Hl(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Hl(e[r],t[r]))return!1;return!0}if(gt(e)&>(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Hl(e[n],t[n]))return!1}return!0}return!1}function gt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Rg{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=fo.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!qs(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new bo(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new bo(e,Error("Configuration must export a valid object"),"unknown");let y={config:Pg(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)fo.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?xi.configLoad(e,l):xi.configLoad(e,Error(String(l)))}};if(o)return Jl.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Cl(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return $S(async()=>qs(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!qs(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=Cl(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Cl(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((t)=>t.test(e))}async validateConfigFile(e){let t=[];try{if(!qs(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Ag{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await Jl.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!aC(t))throw new $o(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new $o(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:PS},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function RS(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class kg{fileLoader=new Rg;envProcessor=new su;validator=new Ag;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)Kt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let a=Date.now()-t;throw Kt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Eo.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(dt(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw xi.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${RS(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?Xs(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)Kt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Kt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Xs(e,r,n):r,c=[dt(li(),".config",e),dt(li(),".config"),li()];for(let a of c){if(n)Kt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)Kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?Xs(e,i,s):i;try{let a=dt(r,"package.json");if(!$x(a))return null;let l={};try{l=JSON.parse(xx(a,"utf8"))}catch(h){if(s)Kt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let u=l[e],f=e;if(!u&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){u=l[d],f=d;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Kt.success(`Configuration loaded from package.json: ${f}`);return{config:Pg(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Kt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xs(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw xi.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return fo.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);fo.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,dt(e,"config"),dt(e,".config"),t?dt(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(dt(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[dt(li(),".config",e),dt(li(),".config"),li()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function Xs(e,t,r=!1){let i=new su,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Eo.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function Dg(e){return Vl.readFileSync(e,"utf8")}function Yl(e,t){let r=[];function i(n){let s;try{s=Vl.readdirSync(n)}catch{return}for(let o of s){let c=$t.join(n,o);try{if(Vl.statSync(c).isDirectory())i(c);else if(o===t)r.push(n)}catch{continue}}}return i(e),r}function A(e,t,r){if(r||fe.verbose)console.debug(`[tlsx:${e}] ${t}`)}function Fg(){return Ng.env.SUDO_PASSWORD}function BS(e){let t=e.toLowerCase();return DS.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function xo(e){if(Array.isArray(e))return e.map((r)=>xo(r));if(typeof e==="string")return FS.test(e)?km:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,i]of Object.entries(e)){if(BS(r)){t[r]=km;continue}t[r]=xo(i)}return t}function Ao(e){return JSON.stringify(xo(e))}function LS(e){let t=Fg();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(e))return e;let r=t.replace(/'/g,"'\\''"),i=e.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${i}`}async function fr(e,t={}){let r=LS(e);try{let{stdout:i,stderr:n}=await NS(r,{cwd:t.cwd||Ng.cwd(),timeout:t.timeout||30000});return{stdout:i.trim(),stderr:n.trim()}}catch(i){let n=Error(`Failed to execute command: ${e}
|
|
125
|
+
Error: ${i.message}`);throw n.stack=i.stack,n}}function Bg(e){if(e.domain)return e.domain;if(e.domains?.length)return e.domains[0];throw Error("Either domain or domains must be specified")}function ou(e){let t=$t.join(kS.homedir(),".stacks","ssl"),r=e.basePath&&e.basePath.trim()!==""?e.basePath:fe.basePath&&fe.basePath.trim()!==""?fe.basePath:t,i=e.certPath?$t.isAbsolute(e.certPath)?e.certPath:$t.join(r,e.certPath):$t.join(r,fe.certPath),n=e.keyPath?$t.isAbsolute(e.keyPath)?e.keyPath:$t.join(r,e.keyPath):$t.join(r,fe.keyPath),s=e.caCertPath?$t.isAbsolute(e.caCertPath)?e.caCertPath:$t.join(r,e.caCertPath):$t.join(r,fe.caCertPath);return{certPath:i,keyPath:n,caCertPath:s,basePath:r}}function Lg(e){let t=[],r=new Set;if(e.domain)r.add(e.domain);if(e.domains?.length)e.domains.forEach((i)=>r.add(i));for(let i of r)t.push({type:2,value:i});if(e.altNameIPs?.length)for(let i of e.altNameIPs)t.push({type:7,ip:i});if(e.altNameURIs?.length)for(let i of e.altNameURIs)t.push({type:6,value:i});if(e.subjectAltNames?.length)t.push(...e.subjectAltNames);return A(k.CERT,`Generated ${t.length} Subject Alternative Names`,e.verbose),t}function au(e){let t=e.notBeforeDays??Ct.DEFAULT_NOT_BEFORE_DAYS,r=e.validityDays??(e.validityYears?e.validityYears*365:Ct.DEFAULT_VALIDITY_DAYS);A(k.CERT,"Calculating certificate validity dates",e.verbose);let i=new Date(Date.now()-86400*t*1000),n=new Date(i.getTime()+r*24*60*60*1000);return i.setUTCHours(0,0,0,0),n.setUTCHours(23,59,59,999),A(k.CERT,`Validity period: ${i.toISOString()} to ${n.toISOString()}`,e.verbose),{notBefore:i,notAfter:n}}function nn(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function it(e,t){let r=nn(t.length);return Buffer.concat([Buffer.from([e]),r,t])}function ln(e){let t=e.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let i=2;i<t.length;i++){let n=t[i],s=[];s.unshift(n&127),n>>=7;while(n>0)s.unshift(n&127|128),n>>=7;r.push(...s)}return it(St.OID,Buffer.from(r))}function zl(e){let t;if(typeof e==="bigint"){let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=e;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return it(St.INTEGER,t)}function Mg(e,t=0){return it(St.BIT_STRING,Buffer.concat([Buffer.from([t]),e]))}function Ig(e){return it(St.OCTET_STRING,e)}function rt(...e){return it(St.SEQUENCE,Buffer.concat(e))}function MS(...e){return it(St.SET,Buffer.concat(e))}function IS(e){return it(St.PRINTABLE_STRING,Buffer.from(e,"ascii"))}function _S(e){return it(St.UTF8_STRING,Buffer.from(e,"utf8"))}function jS(){return Buffer.from([St.NULL,0])}function Om(e,t,r=!0){let i=160|e|(r?0:0),n=nn(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function Nm(e){let t=e.getUTCFullYear();if(t>=2050){let r=e.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return it(St.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),i=(e.getUTCMonth()+1).toString().padStart(2,"0"),n=e.getUTCDate().toString().padStart(2,"0"),s=e.getUTCHours().toString().padStart(2,"0"),o=e.getUTCMinutes().toString().padStart(2,"0"),c=e.getUTCSeconds().toString().padStart(2,"0"),a=`${r}${i}${n}${s}${o}${c}Z`;return it(St.UTC_TIME,Buffer.from(a,"ascii"))}}function US(e,t){return rt(Nm(e),Nm(t))}function Dm(e){let t=[];for(let r of e){let i;switch(r.shortName){case"CN":i=ze.COMMON_NAME;break;case"C":i=ze.COUNTRY;break;case"L":i=ze.LOCALITY;break;case"ST":i=ze.STATE;break;case"O":i=ze.ORGANIZATION;break;case"OU":i=ze.ORGANIZATIONAL_UNIT;break;default:continue}let n=r.shortName==="C"?IS(r.value):_S(r.value),s=rt(ln(i),n);t.push(MS(s))}return rt(...t)}function _g(e){return rt(ln(e),jS())}function WS(e){return e.export({type:"spki",format:"der"})}function KS(e){if(e.includes(":")){let t=e;if(e.includes("::")){let n=e.split("::"),s=n[0]?n[0].split(":"):[],o=n[1]?n[1].split(":"):[],c=8-s.length-o.length,a=Array.from({length:c},()=>"0");t=[...s,...a,...o].join(":")}let r=t.split(":"),i=Buffer.alloc(16);for(let n=0;n<8;n++){let s=Number.parseInt(r[n]||"0",16);i.writeUInt16BE(s,n*2)}return i}else{let t=e.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function HS(e){let t=[];for(let r of e)if(r.type===2&&r.value){let i=nn(r.value.length);t.push(Buffer.concat([Buffer.from([130]),i,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let i=KS(r.ip),n=nn(i.length);t.push(Buffer.concat([Buffer.from([135]),n,i]))}else if(r.type===6&&r.value){let i=nn(r.value.length);t.push(Buffer.concat([Buffer.from([134]),i,Buffer.from(r.value,"ascii")]))}return rt(...t)}function VS(e,t){if(e){if(t!==void 0)return rt(it(1,Buffer.from([255])),zl(t));return rt(it(1,Buffer.from([255])))}return rt()}function YS(e){let t=0;if(e.digitalSignature)t|=128;if(e.keyEncipherment)t|=32;if(e.keyCertSign)t|=4;if(e.cRLSign)t|=2;let r=0,i=t;while(i>0&&(i&1)===0)r++,i>>=1;if(t===0)r=7;return Mg(Buffer.from([t]),r)}function zS(e){let t=[];if(e.serverAuth)t.push(ln(ze.SERVER_AUTH));if(e.clientAuth)t.push(ln(ze.CLIENT_AUTH));return rt(...t)}function tn(e,t,r){let i=[ln(e)];if(t)i.push(it(1,Buffer.from([255])));return i.push(Ig(r)),rt(...i)}function GS(e){let t=[];if(t.push(Om(0,zl(2))),t.push(zl(e.serialNumber)),t.push(_g(ze.SHA256_WITH_RSA)),t.push(Dm(e.issuer)),t.push(US(e.notBefore,e.notAfter)),t.push(Dm(e.subject)),t.push(WS(e.publicKey)),e.extensions){let r=[];if(e.extensions.basicConstraints)r.push(tn(ze.BASIC_CONSTRAINTS,e.extensions.basicConstraints.critical??!0,VS(e.extensions.basicConstraints.isCA,e.extensions.basicConstraints.pathLenConstraint)));if(e.extensions.keyUsage)r.push(tn(ze.KEY_USAGE,e.extensions.keyUsage.critical??!0,YS(e.extensions.keyUsage)));if(e.extensions.extendedKeyUsage)r.push(tn(ze.EXTENDED_KEY_USAGE,!1,zS(e.extensions.extendedKeyUsage)));if(e.extensions.subjectAltName?.length)r.push(tn(ze.SUBJECT_ALT_NAME,!1,HS(e.extensions.subjectAltName)));if(e.extensions.subjectKeyIdentifier)r.push(tn(ze.SUBJECT_KEY_IDENTIFIER,!1,Ig(e.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(Om(3,rt(...r)))}return rt(...t)}function qS(e,t){let r=Ci.createSign("SHA256");r.update(e);let i=r.sign(t);return rt(e,_g(ze.SHA256_WITH_RSA),Mg(i))}function JS(e,t){let r=e.toString("base64"),i=[];for(let n=0;n<r.length;n+=64)i.push(r.slice(n,n+64));return`-----BEGIN ${t}-----
|
|
126
|
+
${i.join(`
|
|
127
127
|
`)}
|
|
128
|
-
-----END ${
|
|
129
|
-
`}function
|
|
130
|
-
`);for(let
|
|
131
|
-
`);for(let
|
|
132
|
-
`).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return O(S.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return O(S.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return O(S.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function EW(w,$,Y){O(S.TRUST,`Adding certificate to system trust store with options: ${_X(Y)}`,Y?.verbose),O(S.TRUST,"Storing certificate and private key",Y?.verbose);let A=rB(w,Y);O(S.TRUST,"Storing CA certificate",Y?.verbose);let X=tB($,Y),J=yX.platform();O(S.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=I7[J];if(!U){let j=`Unsupported platform: ${J}`;throw O(S.TRUST,`Error: ${j}`,Y?.verbose),Error(j)}return await U.addCertificate(X,Y),O(S.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var RF,uf=30000,CX,df="https://acme-staging-v02.api.letsencrypt.org/directory",nf="https://acme-v02.api.letsencrypt.org/directory",WX,LF="1.2.840.10045.2.1",OF="1.2.840.10045.3.1.7",SF="1.2.840.10045.4.3.2",_F="2.5.4.3",hF="1.2.840.113549.1.9.14",DF="2.5.29.17",GX,eU,IE,yE=(w)=>w,VE=(w,$)=>{for(var Y in $)IE(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:CE.bind($,Y)})},LE=(w,$)=>()=>(w&&($=w(w=0)),$),XB,GB,R1,QY,KB,wT,$T,Mf,AX,uU,h0,e,YT,If,AT,yf,XT,JT,LU,UT,Cf,Vf,OU,WT,jT,QT,zT,XX,FB,fT,D0,BT,GT,Lf,JX,vU,N0,u,KT,Of,FT,Sf,ET,TT,SU,NT,_f,hf,qT,_U,HT,RT,MT,IT,yT,UX,EB,CT,VT="0.15.6",ww,NX,UY,cU,mU,qX,gU,dU,WY,nU,lU,B$,TB,NB,Rw,rw,qB,HB,LT,ST,RB,HX,fC,y0,m,BC,hT,GC,DT,KC,FC,Df,EC,xT,kT,TC,xf,NC,qC,HC,RC,MC,hU,ZT,IC,yw,IB,RX,yB,CB,WW,VB,LB,MX,OB,SB,M1,mT,gw,yC,CC,VC,PB,z0,Mw,S,H1,pT,kf="[redacted]",rT,tT,Iw,l0,H7,R7,M7,I7;var sB=s(()=>{RF=HF(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,IE=Object.defineProperty;XB={};VE(XB,{withErrorRecovery:()=>WB,tryLoadConfig:()=>aE,loadConfigWithResult:()=>rE,loadConfig:()=>BB,isRetryableError:()=>mE,isConfigNotFoundError:()=>cE,isBunfigError:()=>jB,globalPerformanceMonitor:()=>QY,globalCache:()=>R1,getEnvOrDefault:()=>gE,generateConfigTypes:()=>sE,defaultGeneratedDir:()=>HB,defaultConfigDir:()=>qB,deepMergeWithArrayStrategy:()=>XW,deepMerge:()=>QB,createLibraryConfig:()=>oE,config:()=>tE,bunfigPlugin:()=>eE,applyEnvVarsToConfig:()=>YY,TypeGenerationError:()=>dU,SchemaValidationError:()=>WY,PluginError:()=>lU,PerformanceMonitor:()=>$W,FileSystemError:()=>gU,ErrorFactory:()=>B$,EnvVarError:()=>qX,EnvProcessor:()=>LX,ConfigValidator:()=>JW,ConfigValidationError:()=>cU,ConfigNotFoundError:()=>NX,ConfigMergeError:()=>mU,ConfigLoader:()=>UW,ConfigLoadError:()=>UY,ConfigFileLoader:()=>OX,ConfigCache:()=>wW,CacheUtils:()=>KB,BunfigError:()=>ww,BrowserConfigError:()=>nU,ArrayMergeStrategies:()=>TB});LT=LE(async()=>{GB=import.meta.require,R1=new wW,QY=new $W,KB={createKey:OE,isEquivalent:SE,estimateMemoryUsage:_E},wT=fX(iU.cwd(),"config"),$T=fX(iU.cwd(),"src/generated"),Mf=zX.env.CLARITY_LOG_DIR||gF(xE(),"logs"),AX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},uU=await kE(),h0={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=h0,YT=h0.red,If=h0.green,AT=h0.yellow,yf=h0.blue,XT=h0.magenta,JT=h0.cyan,LU=h0.white,UT=h0.gray,Cf=h0.bgRed,Vf=h0.bgYellow,OU=h0.bold,WT=h0.dim,jT=h0.italic,QT=h0.underline,zT=h0.reset,XX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},FB={debug:"\uD83D\uDD0D",info:yf("ℹ"),success:If("✓"),warning:Vf(LU(OU(" WARN "))),error:Cf(LU(OU(" ERROR ")))},fT=new FX("stacks"),D0=new FX("bunfig",{showTags:!0}),BT=d0(JY.cwd(),"config"),GT=d0(JY.cwd(),"src/generated"),Lf=QX.env.CLARITY_LOG_DIR||cF(bE(),"logs"),JX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vU=await uE(),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,KT=N0.red,Of=N0.green,FT=N0.yellow,Sf=N0.blue,ET=N0.magenta,TT=N0.cyan,SU=N0.white,NT=N0.gray,_f=N0.bgRed,hf=N0.bgYellow,qT=N0.bgGray,_U=N0.bold,HT=N0.dim,RT=N0.italic,MT=N0.underline,IT=N0.strikethrough,yT=N0.reset,UX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EB={debug:"\uD83D\uDD0D",info:Sf("ℹ"),success:Of("✓"),warning:hf(SU(_U(" WARN "))),error:_f(SU(_U(" ERROR ")))},CT=new TX("stacks"),ww=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 ww{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 ww{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=$}},cU=class extends ww{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},mU=class extends ww{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 ww{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 ww{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 ww{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 ww{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 ww{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 ww{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 cU(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?:\/\//,Rw=new TX("bunfig",{showTags:!0}),rw=new UW,qB=n0(k$.cwd(),"config"),HB=n0(k$.cwd(),"src/generated")});ST=BX.env.CLARITY_LOG_DIR||fE(OT(),"logs"),RB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ST,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},HX={...RB},fC=(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})();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"},m=y0,BC=y0.red,hT=y0.green,GC=y0.yellow,DT=y0.blue,KC=y0.magenta,FC=y0.cyan,Df=y0.white,EC=y0.gray,xT=y0.bgRed,kT=y0.bgYellow,TC=y0.bgGray,xf=y0.bold,NC=y0.dim,qC=y0.italic,HC=y0.underline,RC=y0.strikethrough,MC=y0.reset,hU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ZT={debug:"\uD83D\uDD0D",info:DT("ℹ"),success:hT("✓"),warning:kT(Df(xf(" WARN "))),error:xT(Df(xf(" ERROR ")))};IC=new SX("stacks");yw=class yw 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}`}};IB=class IB extends yw{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 yw{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=$}};yB=class yB extends yw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};CB=class CB extends yw{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 yw{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 yw{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 yw{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 yw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};OB=class OB extends yw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};SB=class SB extends yw{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}};M1={configNotFound(w,$,Y){return new IB(w,$,Y)},configLoad(w,$,Y){return new RX(w,$,Y)},configValidation(w,$,Y){return new yB(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 OB(w,$,Y,A)},plugin(w,$,Y){return new SB(w,$,Y)}};mT=/^https?:\/\//;gw=new SX("bunfig",{showTags:!0});yC=new ZB;CC=Bw(VX.cwd(),"config"),VC=Bw(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(fU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:BU.join(fU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:BU.join(fU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=PB,Mw={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"},S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},H1={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 ]+-----/;Iw={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},l0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};H7={platform:"darwin",async addCertificate(w,$){if(await q7(w,$?.verbose)){O(S.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),H1.success("Certificate is already trusted in system keychain");return}O(S.TRUST,"Adding certificate to macOS keychain",$?.verbose),await f$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;O(S.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await f$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),O(S.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw O(S.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},R7={platform:"win32",async addCertificate(w,$){O(S.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await f$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;O(S.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await f$(`certutil -delstore -enterprise Root "${A}"`),O(S.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw O(S.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},M7={platform:"linux",async addCertificate(w,$){O(S.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=yX.homedir(),A=Mw.LINUX_CERT_DB_FILENAME,X=Mw.LINUX_TRUST_ARGS;O(S.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=tU(Y,A);if(J.length===0){H1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){O(S.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{O(S.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,$?.verbose),await f$(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(j){O(S.TRUST,`Warning: Error deleting existing cert: ${j}`,$?.verbose),console.warn(`Error deleting existing cert: ${j}`)}O(S.TRUST,`Adding new certificate to ${U}`,$?.verbose),await f$(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${w}`),H1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||z0.commonName;O(S.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=yX.homedir(),J=Mw.LINUX_CERT_DB_FILENAME;O(S.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=tU(X,J);if(U.length===0){H1.warn("No certificate databases found. Cannot remove certificate.");return}for(let j of U){O(S.TRUST,`Processing certificate database in ${j}`,$?.verbose);try{await f$(`certutil -d sql:${j} -D -n "${A}"`),H1.info(`Cert removed from ${j}`)}catch(W){O(S.TRUST,`Error removing cert from ${j}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${j}: ${W}`)}}}},I7={darwin:H7,win32:R7,linux:M7}});var xX=s(()=>{sB()});function Z$(w){try{return DX(w)}catch{return null}}function TW(w){try{return KW(w)||null}catch{return null}}function NW(w,$){try{return $.every((Y)=>FW(w,Y))}catch{return!1}}var kX=s(()=>{xX()});import{existsSync as oB,statSync as eB}from"fs";import{existsSync as iW,mkdirSync as _7,readdirSync as h7,writeFileSync as D7}from"fs";import{homedir as y1}from"os";import{dirname as w9,resolve as r0}from"path";import P$ from"process";import{join as x7,relative as k7,resolve as $9}from"path";import sX from"process";import{existsSync as i9,mkdirSync as _V,readdirSync as hV,writeFileSync as DV}from"fs";import{homedir as qW}from"os";import{dirname as ZV,resolve as p0}from"path";import fY from"process";import{join as Z7,relative as P7,resolve as Y9}from"path";import oX from"process";import{existsSync as b9,mkdirSync as vV,readdirSync as cV,writeFileSync as mV}from"fs";import{dirname as dV,resolve as eX}from"path";import bW from"process";import{Buffer as K$}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 v7}from"fs";import{access as c7,constants as U9,mkdir as m7,readdir as ZX,rename as W9,stat as C1,unlink as PX,writeFile as IW}from"fs/promises";import{join as V1}from"path";import x0 from"process";import{pipeline as g7}from"stream/promises";import{createGzip as j9}from"zlib";import L1 from"process";import sw from"process";import{Buffer as tw}from"buffer";import{createCipheriv as d7,createDecipheriv as n7,randomBytes as yW}from"crypto";import{closeSync as CW,createReadStream as Q9,createWriteStream as l7,existsSync as iX,fsyncSync as z9,openSync as f9,writeFileSync as p7}from"fs";import{access as r7,constants as B9,mkdir as t7,readdir as bX,rename as G9,stat as O1,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 K9}from"zlib";import _1 from"process";import ow from"process";import vX from"process";import{existsSync as cX}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 OW,resolve as F9}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 O9,createWriteStream as Qq,existsSync as gX,fsyncSync as S9,openSync as _9,writeFileSync as zq}from"fs";import{access as fq,constants as h9,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 D1,resolve as Kq}from"path";import P from"process";import{pipeline as Fq}from"stream/promises";import{createGzip as x9}from"zlib";import x1 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 zN(){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 zN(),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:L1.pid,hostname:$(),environment:L1.env.NODE_ENV||"development",platform:L1.platform,version:L1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:L1.env.NODE_ENV||L1.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={...vW},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:vW.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 c7(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:K$.from(w);try{if(!MW(this.currentLogFile))await IW(this.currentLogFile,"",{mode:420});if(X=J9(this.currentLogFile,"a",420),v7(X,W,{flag:"a"}),X9(X),X!==void 0)RW(X),X=void 0;if((await C1(this.currentLogFile)).size===0){if(await IW(this.currentLogFile,W,{flag:"w",mode:420}),(await C1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{RW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,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 V1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return V1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return V1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(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=K$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:K$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=j9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(K$.from(K$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(j0())return;let w=await C1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await ZX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await C1(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 IW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await C1(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(V1(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(V1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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],z=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:w0.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:w0.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:Q,tag:z,message:U,level:w}),console.error(f),j){let B=j.split(`
|
|
133
|
-
`);for(let
|
|
134
|
-
`;if(
|
|
135
|
-
`;
|
|
136
|
-
`,
|
|
137
|
-
`),
|
|
138
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
139
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
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=V1(this.config.logDirectory,A);if(w.before)try{if((await C1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await 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 fN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,z]of Object.entries(U)){let f=[...j,Q],B=(F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(B).join("_")}`,T=`${A}_${f.map((F)=>F.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[Q]=J(z,f);else{let F=fY.env[G]||fY.env[T];if(F!==void 0){if(Y)Z0.info(`Using environment variable ${F?G:T} for config ${w}.${f.join(".")}`);if(typeof z==="number")W[Q]=Number(F);else if(typeof z==="boolean")W[Q]=F.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(F);if(Array.isArray(E))W[Q]=E;else W[Q]=F.split(",").map((N)=>N.trim())}catch{W[Q]=F.split(",").map((E)=>E.trim())}else W[Q]=F}}}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)?fN(w,X,J):X,Q=Y||fY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let f=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],F=Array.from(new Set([Q,p0(Q,"config"),p0(Q,".config"),A?p0(Q,A):void 0].filter(Boolean)));for(let E of F){if(J)Z0.info(`Searching for configuration in: ${E}`);let R=[p0(Q,"config"),p0(Q,".config")].concat(A?[p0(Q,A)]:[]).includes(E)?[...f,...B,...G,...T]:[...B,...f,...T,...G];for(let V of R)for(let L of z){let q=p0(E,`${V}${L}`),C=await mX(q,W,j);if(C!==null){if(J)Z0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let E=p0(qW(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)Z0.info(`Checking user config directory: ${E}`);for(let R of N)for(let V of z){let L=p0(E,`${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 E=p0(qW(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=p0(E,`${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 E=qW(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${E}`);for(let R of N)for(let V of z){let L=p0(E,`${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 E=p0(Q,"package.json");if(i9(E)){let N=await import(E),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(E){if(J)Z0.warn("Failed to load package.json:",E)}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 KN(){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 FN(){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 v9{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:_1.pid,hostname:$(),environment:_1.env.NODE_ENV||"development",platform:_1.platform,version:_1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_1.env.NODE_ENV||_1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class 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={...cW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new v9,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:cW.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=f9(this.currentLogFile,"a",420),p7(X,W,{flag:"a"}),z9(X),X!==void 0)CW(X),X=void 0;if((await O1(this.currentLogFile)).size===0){if(await VW(this.currentLogFile,W,{flag:"w",mode:420}),(await O1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{CW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,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 yW(16).toString("hex")}generateKey(){return yW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let 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=yW(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=K9(),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 O1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await bX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await O1(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 O1(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=K9();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=f9(this.currentLogFile,"r+");z9(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()?v.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} ${v.cyan(X)}`;if(!U)return Q.trim();let z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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=v.underline(v.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)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=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 f=this.options.showIcons===!1?"":a9[w],B=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:v.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:v.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
141
|
-
`);for(let
|
|
142
|
-
`;if(
|
|
143
|
-
`;if(
|
|
144
|
-
`);if(this[
|
|
145
|
-
`,
|
|
146
|
-
`),
|
|
147
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
148
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
149
|
-
`)}finishProgressBar(
|
|
128
|
+
-----END ${t}-----
|
|
129
|
+
`}function cu(){let e=Ci.randomBytes(20);return e[0]=e[0]&127||1,e}function jg(e=2048){let{privateKey:t,publicKey:r}=Ci.generateKeyPairSync("rsa",{modulusLength:e});return{privateKey:t,publicKey:r}}function XS(e){let t=e.export({type:"spki",format:"der"});return Ci.createHash("sha1").update(t).digest()}function Ug(e){let t={serialNumber:e.serialNumber||cu(),notBefore:e.notBefore,notAfter:e.notAfter,subject:e.subject,issuer:e.issuer||e.subject,publicKey:e.publicKey,extensions:{basicConstraints:{isCA:e.isCA??!1,critical:!0,pathLenConstraint:e.pathLenConstraint},subjectKeyIdentifier:XS(e.publicKey)}};if(e.keyUsage)t.extensions.keyUsage={...e.keyUsage,critical:!0};if(e.extendedKeyUsage)t.extensions.extendedKeyUsage=e.extendedKeyUsage;if(e.subjectAltName?.length)t.extensions.subjectAltName=e.subjectAltName;let r=GS(t),i=qS(r,e.signingKey);return{certificate:JS(i,"CERTIFICATE"),certificateDer:i}}function Wg(e){return e.export({type:"pkcs8",format:"pem"})}function QS(e){return Ci.createPrivateKey(e)}function ZS(e){let t=new Ci.X509Certificate(e),r=t.publicKey,i=[],n=t.subject.split(`
|
|
130
|
+
`);for(let s of n){let[o,...c]=s.split("="),a=c.join("=");if(o&&a)i.push({shortName:o.trim(),value:a.trim()})}return{publicKey:r,subject:i}}async function lu(e={}){A("ca","Creating new Root CA Certificate",e.verbose);let t=e.keySize||Ct.DEFAULT_KEY_SIZE;A("ca",`Generating ${t}-bit RSA key pair`,e.verbose);let{privateKey:r,publicKey:i}=jg(t),n=[{shortName:"C",value:e.countryName||fe.countryName},{shortName:"ST",value:e.stateName||fe.stateName},{shortName:"L",value:e.localityName||fe.localityName},{shortName:"O",value:e.organization||"Local Development CA"},{shortName:"OU",value:e.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:e.commonName||"Local Development Root CA"}],{notBefore:s,notAfter:o}=au({validityYears:e.validityYears||Ct.DEFAULT_CA_VALIDITY_YEARS,verbose:e.verbose}),{certificate:c}=Ug({serialNumber:cu(),notBefore:s,notAfter:o,subject:n,publicKey:i,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:Wg(r),notBefore:s,notAfter:o}}async function uu(e){if(A("ca","Generating new certificate",e.verbose),A("ca",`Options: ${Ao(e)}`,e.verbose),!e.domain&&!e.domains?.length)throw Error("Either domain or domains must be specified");if(!e.rootCA?.certificate||!e.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=ZS(e.rootCA.certificate),r=QS(e.rootCA.privateKey);A("ca",`Generating ${Ct.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,e.verbose);let i=Ct.DEFAULT_KEY_SIZE,{privateKey:n,publicKey:s}=jg(i),o=e.commonName||Bg(e),c=e.certificateAttributes||[{shortName:"C",value:e.countryName||fe.countryName},{shortName:"ST",value:e.stateName||fe.stateName},{shortName:"L",value:e.localityName||fe.localityName},{shortName:"O",value:e.organizationName||fe.organizationName},{shortName:"CN",value:o}],{notBefore:a,notAfter:l}=au({validityDays:e.validityDays||Ct.DEFAULT_VALIDITY_DAYS,verbose:e.verbose}),u=Lg(e),f=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0},h=e.extKeyUsage||{serverAuth:!0},{certificate:d}=Ug({serialNumber:cu(),notBefore:a,notAfter:l,subject:c,issuer:t,publicKey:s,signingKey:r,isCA:e.basicConstraints?.cA??!1,pathLenConstraint:e.basicConstraints?.pathLenConstraint,keyUsage:f,extendedKeyUsage:h,subjectAltName:u});return{certificate:d,privateKey:Wg(n),notBefore:a,notAfter:l}}function Kg(e,t){A(k.STORAGE,`Storing certificate and private key with options: ${Ao(t)}`,t?.verbose);let{certPath:r,keyPath:i}=ou({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});A(k.STORAGE,`Certificate path: ${r}`,t?.verbose),A(k.STORAGE,`Private key path: ${i}`,t?.verbose);let n=Gl.dirname(r);if(!zt.existsSync(n))A(k.STORAGE,`Creating certificate directory: ${n}`,t?.verbose),zt.mkdirSync(n,{recursive:!0});A(k.STORAGE,"Writing certificate file",t?.verbose),zt.writeFileSync(r,e.certificate);let s=Gl.dirname(i);if(!zt.existsSync(s))A(k.STORAGE,`Creating private key directory: ${s}`,t?.verbose),zt.mkdirSync(s,{recursive:!0});return A(k.STORAGE,"Writing private key file",t?.verbose),zt.writeFileSync(i,e.privateKey),A(k.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function Hg(e,t){A(k.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=ou({basePath:t?.basePath,caCertPath:t?.caCertPath});A(k.STORAGE,`CA certificate path: ${r}`,t?.verbose);let i=Gl.dirname(r);if(!zt.existsSync(i))A(k.STORAGE,`Creating CA certificate directory: ${i}`,t?.verbose),zt.mkdirSync(i,{recursive:!0});return A(k.STORAGE,"Writing CA certificate file",t?.verbose),zt.writeFileSync(r,e),A(k.STORAGE,"CA certificate stored successfully",t?.verbose),r}function ko(e){let t;if(e.startsWith("-----BEGIN CERTIFICATE-----"))t=e;else t=Dg(e);return new e0.X509Certificate(t)}function Oo(e){return ko(e).fingerprint256.replace(/:/g,"").toUpperCase()}function fu(e){return Vg(ko(e).subject)}function t0(e){let t=[],r=e.split(`
|
|
131
|
+
`);for(let i of r){let[n,...s]=i.split("="),o=s.join("=");if(n&&o)t.push({shortName:n.trim(),value:o.trim()})}return t}function Vg(e){return t0(e).find((t)=>t.shortName==="CN")?.value||""}function r0(e){let t=[],r=Vg(e.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let i=e.subjectAltName;if(i){let n=i.split(", ");for(let s of n)if(s.startsWith("DNS:"))t.push(s.slice(4))}return[...new Set(t)]}function hu(e,t){let r=ko(e),i=r0(r);for(let n of i){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2);if(t.endsWith(s)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function n0(e,t){if(Co.platform()!=="darwin")return!1;try{let r=Oo(e);if(!r)return A(k.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(i0("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
132
|
+
`).some((i)=>{let n=i.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!n&&n[1].toUpperCase()===r}))return A(k.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return A(k.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return A(k.TRUST,`Error checking certificate trust: ${r}`,t),!1}}async function du(e,t,r){A(k.TRUST,`Adding certificate to system trust store with options: ${Ao(r)}`,r?.verbose),A(k.TRUST,"Storing certificate and private key",r?.verbose);let i=Kg(e,r);A(k.TRUST,"Storing CA certificate",r?.verbose);let n=Hg(t,r),s=Co.platform();A(k.TRUST,`Detected platform: ${s}`,r?.verbose);let o=c0[s];if(!o){let c=`Unsupported platform: ${s}`;throw A(k.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await o.addCertificate(n,r),A(k.TRUST,"Certificate successfully added to system trust store",r?.verbose),i}var ox,Fm=30000,So,_m="https://acme-staging-v02.api.letsencrypt.org/directory",jm="https://acme-v02.api.letsencrypt.org/directory",so,hx="1.2.840.10045.2.1",dx="1.2.840.10045.3.1.7",mx="1.2.840.10045.4.3.2",gx="2.5.4.3",px="1.2.840.113549.1.9.14",yx="2.5.29.17",fo,Jl,cC,lC=(e)=>e,fC=(e,t)=>{for(var r in t)cC(e,r,{get:t[r],enumerable:!0,configurable:!0,set:uC.bind(t,r)})},hC=(e,t)=>()=>(e&&(t=e(e=0)),t),Zm,cg,$i,un,lg,_C,jC,wm,to,Ll,Ne,ee,UC,vm,WC,bm,KC,HC,Sl,VC,$m,xm,El,YC,zC,GC,qC,ro,ug,JC,De,XC,QC,Cm,io,Ml,ve,j,ZC,Sm,eS,Em,tS,rS,Tl,iS,Tm,Pm,nS,Pl,sS,oS,aS,cS,lS,no,fg,uS,fS="0.15.6",tt,yo,an,Il,_l,wo,jl,Ul,cn,Wl,Kl,hr,hg,dg,xt,Gt,mg,gg,hS,mS,pg,vo,QO,Ee,H,ZO,pS,eN,yS,tN,rN,Rm,iN,wS,vS,nN,Am,sN,oN,aN,cN,lN,Rl,bS,uN,Et,wg,bo,vg,bg,nu,$g,xg,$o,Cg,Sg,xi,PS,Kt,fN,hN,dN,Og,fe,Ct,k,bi,NS,km="[redacted]",DS,FS,St,ze,s0,o0,a0,c0;var Yg=Q(()=>{ox=sx(import.meta.url);So=new sn;so=class so extends Error{problem;httpStatus;constructor(e,t,r){super(e);this.name="AcmeError",this.problem=t,this.httpStatus=r}};fo=new Xm,Jl=new Qm,cC=Object.defineProperty;Zm={};fC(Zm,{withErrorRecovery:()=>rg,tryLoadConfig:()=>BC,loadConfigWithResult:()=>DC,loadConfig:()=>ag,isRetryableError:()=>PC,isConfigNotFoundError:()=>TC,isBunfigError:()=>ig,globalPerformanceMonitor:()=>un,globalCache:()=>$i,getEnvOrDefault:()=>RC,generateConfigTypes:()=>LC,defaultGeneratedDir:()=>gg,defaultConfigDir:()=>mg,deepMergeWithArrayStrategy:()=>tu,deepMerge:()=>ng,createLibraryConfig:()=>MC,config:()=>FC,bunfigPlugin:()=>IC,applyEnvVarsToConfig:()=>rn,TypeGenerationError:()=>Ul,SchemaValidationError:()=>cn,PluginError:()=>Kl,PerformanceMonitor:()=>Ql,FileSystemError:()=>jl,ErrorFactory:()=>hr,EnvVarError:()=>wo,EnvProcessor:()=>To,ConfigValidator:()=>ru,ConfigValidationError:()=>Il,ConfigNotFoundError:()=>yo,ConfigMergeError:()=>_l,ConfigLoader:()=>iu,ConfigLoadError:()=>an,ConfigFileLoader:()=>Po,ConfigCache:()=>Xl,CacheUtils:()=>lg,BunfigError:()=>tt,BrowserConfigError:()=>Wl,ArrayMergeStrategies:()=>hg});hS=hC(async()=>{cg=import.meta.require,$i=new Xl,un=new Ql,lg={createKey:dC,isEquivalent:mC,estimateMemoryUsage:gC},_C=lo(Fl.cwd(),"config"),jC=lo(Fl.cwd(),"src/generated"),wm=co.env.CLARITY_LOG_DIR||Rx(wC(),"logs"),to={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ll=await vC(),Ne={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},ee=Ne,UC=Ne.red,vm=Ne.green,WC=Ne.yellow,bm=Ne.blue,KC=Ne.magenta,HC=Ne.cyan,Sl=Ne.white,VC=Ne.gray,$m=Ne.bgRed,xm=Ne.bgYellow,El=Ne.bold,YC=Ne.dim,zC=Ne.italic,GC=Ne.underline,qC=Ne.reset,ro={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ug={debug:"\uD83D\uDD0D",info:bm("ℹ"),success:vm("✓"),warning:xm(Sl(El(" WARN "))),error:$m(Sl(El(" ERROR ")))},JC=new mo("stacks"),De=new mo("bunfig",{showTags:!0}),XC=Ve(on.cwd(),"config"),QC=Ve(on.cwd(),"src/generated"),Cm=ao.env.CLARITY_LOG_DIR||Tx(CC(),"logs"),io={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Cm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ml=await SC(),ve={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},j=ve,ZC=ve.red,Sm=ve.green,eS=ve.yellow,Em=ve.blue,tS=ve.magenta,rS=ve.cyan,Tl=ve.white,iS=ve.gray,Tm=ve.bgRed,Pm=ve.bgYellow,nS=ve.bgGray,Pl=ve.bold,sS=ve.dim,oS=ve.italic,aS=ve.underline,cS=ve.strikethrough,lS=ve.reset,no={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fg={debug:"\uD83D\uDD0D",info:Em("ℹ"),success:Sm("✓"),warning:Pm(Tl(Pl(" WARN "))),error:Tm(Tl(Pl(" ERROR ")))},uS=new po("stacks"),tt=class extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},yo=class extends tt{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},an=class extends tt{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Il=class extends tt{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},_l=class extends tt{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},wo=class extends tt{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},jl=class extends tt{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Ul=class extends tt{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},cn=class extends tt{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Wl=class extends tt{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Kl=class extends tt{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},hr={configNotFound(e,t,r){return new yo(e,t,r)},configLoad(e,t,r){return new an(e,t,r)},configValidation(e,t,r){return new Il(e,t,r)},configMerge(e,t,r,i){return new _l(e,t,r,i)},envVar(e,t,r,i){return new wo(e,t,r,i)},fileSystem(e,t,r){return new jl(e,t,r)},typeGeneration(e,t,r){return new Ul(e,t,r)},schemaValidation(e,t,r){return new cn(e,t,r)},browserConfig(e,t,r,i){return new Wl(e,t,r,i)},plugin(e,t,r){return new Kl(e,t,r)}},hg={replace:"replace",concat:"concat",smart:"smart"},dg=/^https?:\/\//,xt=new po("bunfig",{showTags:!0}),Gt=new iu,mg=Ye(Fr.cwd(),"config"),gg=Ye(Fr.cwd(),"src/generated")});mS=uo.env.CLARITY_LOG_DIR||Jx(dS(),"logs"),pg={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mS,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vo={...pg},QO=(async()=>{try{let{loadConfig:e}=await hS().then(()=>Zm),t=await e({name:"clarity",alias:"logging",defaultConfig:pg,cwd:uo.cwd()});if(t)Object.assign(vo,t)}catch{}return vo})();Ee={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},H=Ee,ZO=Ee.red,pS=Ee.green,eN=Ee.yellow,yS=Ee.blue,tN=Ee.magenta,rN=Ee.cyan,Rm=Ee.white,iN=Ee.gray,wS=Ee.bgRed,vS=Ee.bgYellow,nN=Ee.bgGray,Am=Ee.bold,sN=Ee.dim,oN=Ee.italic,aN=Ee.underline,cN=Ee.strikethrough,lN=Ee.reset,Rl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bS={debug:"\uD83D\uDD0D",info:yS("ℹ"),success:pS("✓"),warning:vS(Rm(Am(" WARN "))),error:wS(Rm(Am(" ERROR ")))};uN=new Ro("stacks");Et=class Et extends Error{timestamp;context;constructor(e,t={}){super(e);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}};wg=class wg extends Et{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}};bo=class bo extends Et{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}};vg=class vg extends Et{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}};bg=class bg extends Et{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}};nu=class nu extends Et{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}};$g=class $g extends Et{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}};xg=class xg extends Et{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}};$o=class $o extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}};Cg=class Cg extends Et{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}};Sg=class Sg extends Et{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}};xi={configNotFound(e,t,r){return new wg(e,t,r)},configLoad(e,t,r){return new bo(e,t,r)},configValidation(e,t,r){return new vg(e,t,r)},configMerge(e,t,r,i){return new bg(e,t,r,i)},envVar(e,t,r,i){return new nu(e,t,r,i)},fileSystem(e,t,r){return new $g(e,t,r)},typeGeneration(e,t,r){return new xg(e,t,r)},schemaValidation(e,t,r){return new $o(e,t,r)},browserConfig(e,t,r,i){return new Cg(e,t,r,i)},plugin(e,t,r){return new Sg(e,t,r)}};PS=/^https?:\/\//;Kt=new Ro("bunfig",{showTags:!0});fN=new kg;hN=dt(Eo.cwd(),"config"),dN=dt(Eo.cwd(),"src/generated"),Og={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:ll.join(cl.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ll.join(cl.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ll.join(cl.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},fe=Og,Ct={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"},k={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},bi={info:(...e)=>console.log(...e),warn:(...e)=>console.warn(...e),success:(...e)=>console.log(...e),error:(...e)=>console.error(...e),debug:(...e)=>console.debug(...e)};NS=OS(AS);DS=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),FS=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;St={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},ze={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"};s0={platform:"darwin",async addCertificate(e,t){if(await n0(e,t?.verbose)){A(k.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),bi.success("Certificate is already trusted in system keychain");return}A(k.TRUST,"Adding certificate to macOS keychain",t?.verbose),await fr(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${e}`)},async removeCertificate(e,t,r){let i=r||fe.commonName;A(k.TRUST,`Removing certificate ${i} from macOS keychain`,t?.verbose);try{await fr(`sudo security delete-certificate -c "${i}" /Library/Keychains/System.keychain`),A(k.TRUST,`Removed certificate ${i} from macOS keychain`,t?.verbose)}catch(n){throw A(k.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},o0={platform:"win32",async addCertificate(e,t){A(k.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await fr(`certutil -f -v -addstore -enterprise Root ${e}`)},async removeCertificate(e,t,r){let i=r||fe.commonName;A(k.TRUST,`Removing certificate ${i} from Windows certificate store`,t?.verbose);try{await fr(`certutil -delstore -enterprise Root "${i}"`),A(k.TRUST,`Removed certificate ${i} from Windows certificate store`,t?.verbose)}catch(n){throw A(k.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},a0={platform:"linux",async addCertificate(e,t){A(k.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=Co.homedir(),i=Ct.LINUX_CERT_DB_FILENAME,n=Ct.LINUX_TRUST_ARGS;A(k.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let s=Yl(r,i);if(s.length===0){bi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let o of s){A(k.TRUST,`Processing certificate database in ${o}`,t?.verbose);try{A(k.TRUST,`Attempting to delete existing cert for ${fe.commonName}`,t?.verbose),await fr(`certutil -d sql:${o} -D -n ${fe.commonName}`)}catch(c){A(k.TRUST,`Warning: Error deleting existing cert: ${c}`,t?.verbose),console.warn(`Error deleting existing cert: ${c}`)}A(k.TRUST,`Adding new certificate to ${o}`,t?.verbose),await fr(`certutil -d sql:${o} -A -t ${n} -n ${fe.commonName} -i ${e}`),bi.info(`Cert added to ${o}`)}},async removeCertificate(e,t,r){let i=r||fe.commonName;A(k.TRUST,`Removing certificate ${i} from Linux certificate store`,t?.verbose);let n=Co.homedir(),s=Ct.LINUX_CERT_DB_FILENAME;A(k.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let o=Yl(n,s);if(o.length===0){bi.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of o){A(k.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{await fr(`certutil -d sql:${c} -D -n "${i}"`),bi.info(`Cert removed from ${c}`)}catch(a){A(k.TRUST,`Error removing cert from ${c}: ${a}`,t?.verbose),console.warn(`Error removing cert from ${c}: ${a}`)}}}},c0={darwin:s0,win32:o0,linux:a0}});var No=Q(()=>{Yg()});function Br(e){try{return Oo(e)}catch{return null}}function mu(e){try{return fu(e)||null}catch{return null}}function gu(e,t){try{return t.every((r)=>hu(e,r))}catch{return!1}}var Do=Q(()=>{No()});import{existsSync as zg,statSync as Gg}from"fs";import{existsSync as Fu,mkdirSync as g0,readdirSync as p0,writeFileSync as y0}from"fs";import{homedir as Si}from"os";import{dirname as qg,resolve as qe}from"path";import Lr from"process";import{join as w0,relative as v0,resolve as Jg}from"path";import Jo from"process";import{existsSync as Np,mkdirSync as yD,readdirSync as wD,writeFileSync as vD}from"fs";import{homedir as pu}from"os";import{dirname as xD,resolve as Ge}from"path";import hn from"process";import{join as b0,relative as $0,resolve as Xg}from"path";import Xo from"process";import{existsSync as Dp,mkdirSync as PD,readdirSync as RD,writeFileSync as AD}from"fs";import{dirname as OD,resolve as Qo}from"path";import Bu from"process";import{Buffer as mr}from"buffer";import{createCipheriv as x0,createDecipheriv as C0,randomBytes as yu}from"crypto";import{closeSync as wu,createReadStream as Qg,createWriteStream as S0,existsSync as vu,fsyncSync as Zg,openSync as ep,writeFileSync as E0}from"fs";import{access as T0,constants as tp,mkdir as P0,readdir as Fo,rename as rp,stat as Ei,unlink as Bo,writeFile as bu}from"fs/promises";import{join as Ti}from"path";import Fe from"process";import{pipeline as R0}from"stream/promises";import{createGzip as ip}from"zlib";import Pi from"process";import Xt from"process";import{Buffer as qt}from"buffer";import{createCipheriv as A0,createDecipheriv as k0,randomBytes as $u}from"crypto";import{closeSync as xu,createReadStream as np,createWriteStream as O0,existsSync as Lo,fsyncSync as sp,openSync as op,writeFileSync as N0}from"fs";import{access as D0,constants as ap,mkdir as F0,readdir as Mo,rename as cp,stat as Ri,unlink as Io,writeFile as Cu}from"fs/promises";import{isAbsolute as B0,join as Ai,resolve as L0}from"path";import L from"process";import{pipeline as M0}from"stream/promises";import{createGzip as lp}from"zlib";import ki from"process";import Qt from"process";import _o from"process";import{existsSync as jo}from"fs";import{resolve as Su}from"path";import{existsSync as I0}from"fs";import{existsSync as _0,readdirSync as j0}from"fs";import{extname as Eu,resolve as up}from"path";import U0 from"process";import{join as WE,relative as KE,resolve as xp}from"path";import sa from"process";import{Buffer as Jt}from"buffer";import{createCipheriv as YE,createDecipheriv as zE,randomBytes as ku}from"crypto";import{closeSync as Ou,createReadStream as Cp,createWriteStream as GE,existsSync as Wo,fsyncSync as Sp,openSync as Ep,writeFileSync as qE}from"fs";import{access as JE,constants as Tp,mkdir as XE,readdir as Ko,rename as Pp,stat as Oi,unlink as Ho,writeFile as Nu}from"fs/promises";import{isAbsolute as QE,join as Ni,resolve as ZE}from"path";import M from"process";import{pipeline as eT}from"stream/promises";import{createGzip as Rp}from"zlib";import Di from"process";import Zt from"process";function h0(e,t){this[e]=f0.bind(null,t)}class Vu{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!zg(e))return!0;return Gg(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=zg(r)?Gg(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.timestamp).sort();return{size:t,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:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Yu{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function W0(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function K0(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function H0(e){return e.getStats().size*2}function zu(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&se(t[0])&&"id"in t[0]&&t[0].id===3&&se(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(se(t)&&se(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(se(e)&&"arr"in e&&Array.isArray(e.arr)&&se(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&se(t[0])&&se(e[0])){let i=[...t];for(let n of e)if(se(n)&&"name"in n){if(!i.find((o)=>se(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(se(n)&&"path"in n){if(!i.find((o)=>se(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>Zo(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!se(t)||!se(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(se(n)&&se(r[i]))r[i]=zu(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&se(n[0])&&se(r[i][0])){let s=[...n];for(let o of r[i])if(se(o)&&"name"in o){if(!s.find((a)=>se(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(se(o)&&"path"in o){if(!s.find((a)=>se(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>Zo(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Zo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Zo(e[r],t[r]))return!1;return!0}if(se(e)&&se(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Zo(e[n],t[n]))return!1}return!0}return!1}function se(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function V0(e,t){if(!Dp(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return zu(t,i)}catch{return null}}catch{return null}}async function Y0({name:e="",cwd:t,defaultConfig:r}){let i=t||Bu.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let c of n){let a=Qo(i,`${o}${c}`),l=await V0(a,r);if(l!==null)return l}try{let o=Qo(i,"package.json");if(Dp(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return zu(r,a)}catch{}}}catch{}return r}function z0(e,t={}){let r=Xo.cwd();while(r.includes("storage"))r=Xg(r,"..");let i=Xg(r,e||"");if(t?.relative)return $0(Xo.cwd(),i);return i}async function G0(){try{let e=await Y0({name:"clarity",defaultConfig:Yo,cwd:Xo.cwd(),endpoint:"",headers:{}});return{...Yo,...e}}catch{return Yo}}function le(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function q0(){if(Xt.env.NODE_ENV==="test"||Xt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Xt<"u"){let e=Xt.type;if(e==="renderer"||e==="worker")return!1;return!!(Xt.versions&&(Xt.versions.node||Xt.versions.bun))}return!1}class Fp{async format(e){let t=await q0(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Pi.pid,hostname:t(),environment:Pi.env.NODE_ENV||"development",platform:Pi.platform,version:Pi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pi.env.NODE_ENV||Pi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ea{name;fileLocks=new Map;currentKeyId=null;keys=new Map;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(e,t={}){this.name=e,this.config={...Mu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Fp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??Fe.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...zo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...zo};return{...zo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Mu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await T0(this.config.logDirectory,tp.F_OK|tp.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await P0(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:mr.from(e);try{if(!vu(this.currentLogFile))await bu(this.currentLogFile,"",{mode:420});if(n=ep(this.currentLogFile,"a",420),E0(n,a,{flag:"a"}),Zg(n),n!==void 0)wu(n),n=void 0;if((await Ei(this.currentLogFile)).size===0){if(await bu(this.currentLogFile,a,{flag:"w",mode:420}),(await Ei(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{wu(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Ti(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 Ti(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ti(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(le())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}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 e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=yu(16),i=x0("aes-256-gcm",t,r),n=mr.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:mr.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ip(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(mr.from(mr.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(le())return;let e=await Ei(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Fo(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Ei(r).catch(()=>null))try{if(await rp(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Bo(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await bu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ei(r).catch(()=>null))await rp(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Fo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Bo(Ti(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Qg(e),i=S0(t),n=ip();await R0(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),vu(this.currentLogFile))try{let e=ep(this.currentLogFile,"r+");Zg(e),wu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!le()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Fo(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Bo(Ti(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?te.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=Fe.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${te.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!le()){let l=Hp[e],u=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",f;switch(e){case"debug":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:te.gray(o),level:e}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:te.green(o),level:e}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:n,icon:l,tag:u,message:o,level:e}),console.error(f),c){let h=c.split(`
|
|
133
|
+
`);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:te.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!le()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let a=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
|
|
134
|
+
`;if(c)a+=`${c}
|
|
135
|
+
`;a=a.replace(this.ANSI_PATTERN,""),await this.writeToFile(a)}time(e){let t=performance.now();if(this.fancy&&!le()){let r=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:te.blue("◐"),tag:r,message:`${te.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
136
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!le()){let u=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:te.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!le())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ea(t,{...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(r),r}createReadStream(){if(le())throw Error("createReadStream is not supported in browser environments");if(!vu(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Qg(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=mr.isBuffer(e)?e:mr.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),c=C0("aes-256-gcm",r,n);return c.setAuthTag(s),mr.concat([c.update(o),c.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return le()}isServerMode(){return!le()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!le()){let s=e.split(`
|
|
137
|
+
`),o=Math.max(...s.map((u)=>u.length))+2,c=`┌${"─".repeat(o)}┐`,a=`└${"─".repeat(o)}┘`,l=s.map((u)=>{let f=" ".repeat(o-u.length-2);return`│ ${u}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:te.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(c)})),l.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:te.cyan(a),showTimestamp:!1}))}else if(!le())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
|
|
138
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(le())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${te.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();Fe.stdin.removeListener("data",r);try{if(typeof Fe.stdin.setRawMode==="function")Fe.stdin.setRawMode(!1)}catch{}Fe.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof Fe.stdin.setRawMode==="function")Fe.stdin.setRawMode(!0)}catch{}Fe.stdin.resume(),Fe.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,c=0;if(r=e.replace(o,(a,l)=>{if(l==="%")return"%";if(c>=t.length)return a;let u=t[c++];switch(l){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return a}}),c<t.length)r+=` ${t.slice(c).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}if(this.fancy&&!le()){let o=this.options.showTags!==!1&&this.name?te.gray(this.formatTag(this.name)):"",c=te.blue("◐");console.error(`${c} ${o} ${te.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
139
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||le()||e<=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 r=20;return this.activeProgressBar={total:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||le())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),c!==void 0)this.activeProgressBar.message=c;let a=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,a)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||le())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||le())return;Fe.stdout.write(`${"\r".padEnd(Fe.stdout.columns||80)}\r`),this.log(c,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||le()||!Fe.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=te.green("━".repeat(i)),o=te.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=t||r===100?te.green("✓"):te.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${te.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=Fe.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,Fe.stdout.write(e.lastRenderedLine),t)Fe.stdout.write(`
|
|
140
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||le()||!Fe.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(le()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Fo(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Ti(this.config.logDirectory,i);if(e.before)try{if((await Ei(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Bo(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Vo(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&X(t[0])&&"id"in t[0]&&t[0].id===3&&X(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(X(t)&&X(e)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(X(e)&&"arr"in e&&Array.isArray(e.arr)&&X(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&X(t[0])&&X(e[0])){let i=[...t];for(let n of e)if(X(n)&&"name"in n){if(!i.find((o)=>X(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(X(n)&&"path"in n){if(!i.find((o)=>X(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>ta(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!X(t)||!X(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(X(n)&&X(r[i]))r[i]=Vo(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&X(n[0])&&X(r[i][0])){let s=[...n];for(let o of r[i])if(X(o)&&"name"in o){if(!s.find((a)=>X(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(X(o)&&"path"in o){if(!s.find((a)=>X(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((c)=>ta(c,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function Gu(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:Vo(e,t);if(Array.isArray(e))return r==="replace"?t:Vo(e,t);if(!X(t)||!X(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=Vo(o,s);else if(X(s)&&X(o))i[n]=Gu(o,s,r);else i[n]=s}return i}function ta(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ta(e[r],t[r]))return!1;return!0}if(X(e)&&X(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ta(e[n],t[n]))return!1}return!0}return!1}function X(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Uo(e,t,r="replace"){if(!Np(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Gu(t,n,r)}catch{return null}}catch{return null}}function J0(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${f.map(h).join("_")}`,y=`${i}_${f.map((g)=>g.toUpperCase()).join("_")}`;if(r)Le.info(`Checking environment variable ${d} for config ${e}.${f.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))a[l]=s(u,f);else{let g=hn.env[d]||hn.env[y];if(g!==void 0){if(r)Le.info(`Using environment variable ${g?d:y} for config ${e}.${f.join(".")}`);if(typeof u==="number")a[l]=Number(g);else if(typeof u==="boolean")a[l]=g.toLowerCase()==="true";else if(Array.isArray(u))try{let p=JSON.parse(g);if(Array.isArray(p))a[l]=p;else a[l]=g.split(",").map((w)=>w.trim())}catch{a[l]=g.split(",").map((p)=>p.trim())}else a[l]=g}}}return a}return s(n)}async function X0({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:c="replace"}){let a=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?J0(e,n,s):n,l=r||hn.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(s)Le.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let f=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],y=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ge(l,"config"),Ge(l,".config"),i?Ge(l,i):void 0].filter(Boolean)));for(let p of g){if(s)Le.info(`Searching for configuration in: ${p}`);let b=[Ge(l,"config"),Ge(l,".config")].concat(i?[Ge(l,i)]:[]).includes(p)?[...f,...h,...d,...y]:[...h,...f,...y,...d];for(let P of b)for(let R of u){let v=Ge(p,`${P}${R}`),T=await Uo(v,a,c);if(T!==null){if(s)Le.success(`Configuration loaded from: ${v}`);return T}}}if(e){let p=Ge(pu(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)Le.info(`Checking user config directory: ${p}`);for(let b of w)for(let P of u){let R=Ge(p,`${b}${P}`),v=await Uo(R,a,c);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory: ${R}`);return v}}}if(e){let p=Ge(pu(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)Le.info(`Checking user config directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ge(p,`${b}${P}`),v=await Uo(R,a,c);if(v!==null){if(s)Le.success(`Configuration loaded from user config directory dotfile: ${R}`);return v}}}if(e){let p=pu(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)Le.info(`Checking user home directory for dotfile configs: ${p}`);for(let b of w)for(let P of u){let R=Ge(p,`${b}${P}`),v=await Uo(R,a,c);if(v!==null){if(s)Le.success(`Configuration loaded from user home directory: ${R}`);return v}}}try{let p=Ge(l,"package.json");if(Np(p)){let w=await import(p),b=w[e];if(!b&&t){if(b=w[t],b&&s)Le.success(`Using alias "${t}" configuration from package.json`)}if(b&&typeof b==="object"&&!Array.isArray(b))try{if(s)Le.success(`Configuration loaded from package.json: ${b===w[e]?e:t}`);return Gu(a,b,c)}catch(P){if(s)Le.warn("Failed to merge package.json config:",P)}}}catch(p){if(s)Le.warn("Failed to load package.json:",p)}if(s)Le.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return a}function Q0(e,t={}){let r=Jo.cwd();while(r.includes("storage"))r=Jg(r,"..");let i=Jg(r,e||"");if(t?.relative)return v0(Jo.cwd(),i);return i}async function Z0(){try{let e=await X0({name:"clarity",alias:"logging",defaultConfig:Go,cwd:Jo.cwd()});return{...Go,...e||{}}}catch{return Go}}function $e(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eE(){if(Qt.env.NODE_ENV==="test"||Qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Qt<"u"){let e=Qt.type;if(e==="renderer"||e==="worker")return!1;return!!(Qt.versions&&(Qt.versions.node||Qt.versions.bun))}return!1}class Bp{async format(e){let t=await eE(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:ki.pid,hostname:t(),environment:ki.env.NODE_ENV||"development",platform:ki.platform,version:ki.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ki.env.NODE_ENV||ki.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ra{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(e,t={}){this.name=e,this.config={...Iu},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Bp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...qo,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...qo};return{...qo,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Iu.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!$e()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await D0(this.config.logDirectory,ap.F_OK|ap.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await F0(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:qt.from(e);try{if(!Lo(this.currentLogFile))await Cu(this.currentLogFile,"",{mode:420});if(n=op(this.currentLogFile,"a",420),N0(n,a,{flag:"a"}),sp(n),n!==void 0)xu(n),n=void 0;if((await Ri(this.currentLogFile)).size===0){if(await Cu(this.currentLogFile,a,{flag:"w",mode:420}),(await Ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{xu(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Ai(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 Ai(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ai(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if($e())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return $u(16).toString("hex")}generateKey(){return $u(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=$u(16),i=A0("aes-256-gcm",t,r),n=qt.isBuffer(e)?e:qt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=qt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=lp(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(qt.from(qt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if($e())return;if(!this.shouldWriteToFile())return;let e=await Ri(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Mo(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Ri(r).catch(()=>null))try{if(await cp(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Io(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Cu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ri(r).catch(()=>null))await cp(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Mo(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Io(Ai(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=np(e),i=O0(t),n=lp();await M0(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Lo(this.currentLogFile))try{let e=op(this.currentLogFile,"r+");sp(e),xu(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!$e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Mo(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Io(Ai(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?U.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||$e())return!1;let e=typeof L.env.NO_COLOR<"u",t=L.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=L.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${U.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=U.underline(U.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>U.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>U.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>U.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>U.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>U.strikethrough(i)),t}supportsHyperlinks(){if($e())return!1;let e=L.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=L.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(B0(t)||t.startsWith("./")||t.startsWith("../"))t=L0(t);else return null;return Lo(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":Vp[e],h=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:U.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:U.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
141
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:U.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!$e()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}if(!this.shouldLog(e))return;let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
142
|
+
`;if(c)u+=`${c}
|
|
143
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!$e()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!$e()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!$e()&&L.stdout.isTTY)L.stdout.write(`
|
|
144
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!$e()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":U.blue("◐"),tag:r,message:`${U.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
145
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":U.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!$e())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ra(t,{...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(r),r}createReadStream(){if($e())throw Error("createReadStream is not supported in browser environments");if(!Lo(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return np(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=qt.isBuffer(e)?e:qt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),c=k0("aes-256-gcm",r,n);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=qt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return $e()}isServerMode(){return!$e()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
146
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:U.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(u),showTimestamp:!1}))}else if(!$e())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
147
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if($e())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${U.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();L.stdin.removeListener("data",r);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${U.blue("◐")} `;console.error(`${l}${a} ${U.cyan(i)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
148
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=U.green("━".repeat(i)),o=U.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?U.green("✓"):U.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${U.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=L.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,L.stdout.write(e.lastRenderedLine),t)L.stdout.write(`
|
|
149
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||$e()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if($e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Mo(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Ai(this.config.logDirectory,i);if(e.before)try{if((await Ri(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Io(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Lp(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await e()}catch(a){if(o=a instanceof Error?a:Error(String(a)),c===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Mp(e){return e instanceof nt}function tE(e){return e instanceof ia}function rE(e){if(Mp(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class aa{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:c=!1,trackPerformance:a=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let u=i||this.generateEnvPrefix(e),f={...t};return this.processObject(f,[],u,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:c,configName:e}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(a)return gn.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=o.map((u)=>this.formatEnvKey(u,i.useCamelCase)),a=`${r}_${c.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((u)=>u.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let u=_o.env[a]||(l?_o.env[l]:void 0);if(u!==void 0){if(i.verbose){let f=_o.env[a]?a:l}try{e[n]=this.parseEnvironmentValue(u,typeof s,a,i.customParsers,i.configName)}catch(f){if(f instanceof na)throw f;throw gr.envVar(a,u,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw gr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(_o.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],c=`${r}_${o.map((a)=>this.formatEnvKey(a,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:c,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
|
|
150
150
|
|
|
151
|
-
`;for(let
|
|
152
|
-
`,
|
|
153
|
-
`,
|
|
154
|
-
`,
|
|
151
|
+
`;for(let i of e)r+=`${i.key}
|
|
152
|
+
`,r+=` Type: ${i.type}
|
|
153
|
+
`,r+=` Description: ${i.description}
|
|
154
|
+
`,r+=` Example: ${i.example}
|
|
155
155
|
|
|
156
|
-
`;return
|
|
156
|
+
`;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
|
|
157
157
|
|
|
158
|
-
`;
|
|
159
|
-
`,
|
|
160
|
-
`;for(let
|
|
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(!Fw($)||!Fw(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(Fw($[0])&&Fw(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(!Fw(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)=>Fw(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(Fw(X)&&A.has(X))return A.get(X);let J={...w};if(Fw(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(Fw(j)&&Fw(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(Fw(w)&&Fw($)){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 Fw(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=k1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!cX(w))return null;try{let Q=`?t=${Date.now()}`,z=await import(w+Q),f=z.default||z,B="default"in z,G=Object.keys(z).length>0;if(!B&&!G)throw new BY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new BY(w,Error("Configuration must export a valid object"),"unknown");let E={config:oW($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)k1.setWithFileCheck("file",E,w,J);return E}catch(Q){throw Q instanceof Error?F$.configLoad(w,Q):F$.configLoad(w,Error(String(Q)))}};if(U)return KY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(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 c9(async()=>{return cX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!cX(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(!cX(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 z=[],f=[],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 z.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:z,warnings:f}}};if(j)return await KY.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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!z&&(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||z))throw W;if(f&&(!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)Cw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Cw.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:z=!1}=w,f=J||P$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,f,U,j,Q,z,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,B,W,A,z);let T=await this.loadHomeConfiguration(A,X,j,Q,z,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,z);let F=await this.loadPackageJsonConfiguration(A,X,f,j,Q,z,W);if(F)return B.push(r0(f,"package.json")),this.finalizeResult(F,B,W,A,z);if(B.push(...this.getAllSearchPaths(A,X,f,U)),$)throw F$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?zY(w,X,U):X,z=this.getLocalDirectories(Y,A);for(let f of z){if(U)Cw.info(`Searching for configuration in: ${f}`);let B=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Cw.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?zY(w,Y,X):Y,j=[r0(y1(),".config",w),r0(y1(),".config"),y1()];for(let W of j){if(X)Cw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),z=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(z){if(X)Cw.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?zY(w,A,J):A;try{let W=r0(Y,"package.json");if(!iW(W))return null;let Q=await import(W),z=Q[w],f=w;if(!z&&$)z=Q[$],f=$;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)Cw.success(`Configuration loaded from package.json: ${f}`);return{config:oW(j,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Cw.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:zY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw F$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return k1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);k1.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,r0(w,"config"),r0(w,".config"),$?r0(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(r0(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=[r0(y1(),".config",w),r0(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 E9(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 IN(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)Cw.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 yN(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"&&E9(Y)))return(await w$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await w$.loadConfig({...w,cwd:w.cwd||P$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&E9($)))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 zY(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,z]of Object.entries(U)){let f=[...j,Q],B=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((F)=>F.toUpperCase()).join("")}`,`${X}_${f.map((F)=>F.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let F of B)if(G=P$.env[F],G!==void 0){T=F;break}if(G!==void 0&&T)if(typeof z==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof z==="number"){let F=Number(G);if(!Number.isNaN(F))W[Q]=F}else if(Array.isArray(z))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((F)=>F.trim())}else W[Q]=G;else if(z&&typeof z==="object"&&!Array.isArray(z))W[Q]=J(z,f)}return W}return J($)}function VN(w){let $=r0(P$.cwd(),w.configDir),Y=r0(P$.cwd(),w.generatedDir),A=r0(Y,"config-types.ts");if(!iW(w9(A)))_7(w9(A),{recursive:!0,mode:511});let X=iW($)?h7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${$q}
|
|
162
|
-
export type ConfigNames = ${
|
|
163
|
-
`;
|
|
164
|
-
${
|
|
158
|
+
`;r+=`| Variable | Type | Description | Example |
|
|
159
|
+
`,r+=`|----------|------|-------------|----------|
|
|
160
|
+
`;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
|
|
161
|
+
`;return r}}function iE(e,t){let r=Wp("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function Ip(e,t,r={}){return _p(e,t,r,new WeakMap)}function _p(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let c=o(e,t);if(c!==void 0)return c}if(Array.isArray(t)||Array.isArray(e))return jp(e,t,n,i);if(!pt(t)||!pt(e))return t;return aE(e,t,r,i)}function jp(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return nE(e,t);case"smart":return sE(e,t,i);default:return t}return t}function nE(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Lu(n,i)))r.push(i);return r}function sE(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(pt(t[0])&&pt(e[0]))return oE(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function oE(e,t,r){let i=[...t];for(let n of e){if(!pt(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let c of s)if(c in n){if(i.find((l)=>pt(l)&&(c in l)&&l[c]===n[c])){o=!0;break}}if(!o)i.push(n)}return i}function aE(e,t,r,i){let n=t;if(pt(n)&&i.has(n))return i.get(n);let s={...e};if(pt(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let c=n[o],a=s[o];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){s[o]=c;continue}if(pt(c)&&pt(a))s[o]=_p(a,c,r,i);else if(Array.isArray(c)||Array.isArray(a))s[o]=jp(a,c,r.arrayMergeMode||"smart",i);else s[o]=c}return s}function qu(e,t,r="replace"){return Ip(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Lu(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Lu(e[r],t[r]))return!1;return!0}if(pt(e)&&pt(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Lu(e[n],t[n]))return!1}return!0}return!1}function pt(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ca{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:c=!1}=r;if(n){let l=Fi.getWithFileCheck("file",e);if(l){if(c)console.log(`Configuration loaded from cache: ${e}`);return l}}let a=async()=>{if(!jo(e))return null;try{let l=`?t=${Date.now()}`,u=await import(e+l),f=u.default||u,h="default"in u,d=Object.keys(u).length>0;if(!h&&!d)throw new dn(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new dn(e,Error("Configuration must export a valid object"),"unknown");let p={config:qu(t,f,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Fi.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?gr.configLoad(e,l):gr.configLoad(e,Error(String(l)))}};if(o)return gn.track("loadFromPath",a,{path:e});return a()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Su(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Lp(async()=>jo(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!jo(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let c=Su(e,`${s}${o}`);if(await this.checkFileAccess(c))i.push(c)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let c=Su(e,o);if(await this.checkFileAccess(c))i.push(c)}}catch{return[]}return i}looksLikeConfigFile(e){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((r)=>r.test(e))}async validateConfigFile(e){let t=[];try{if(!jo(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class Ju{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:c=!0,verbose:a=!1}=r,l=async()=>{let u=[],f=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:c,verbose:a};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return u.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:u,warnings:f}}};if(c)return await gn.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!I0(t))throw new mn(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new mn(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,c=Array.isArray(t.type)?t.type:[t.type];if(!c.includes(o)){if(i.push({path:r,message:`Expected type ${c.join(" or ")}, got ${o}`,expected:c.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let c=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,c,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let c of t.required)if(!(c in o)){if(i.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[c,a]of Object.entries(t.properties))if(c in o){let l=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(o[c],a,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let c=new Set(Object.keys(t.properties||{}));for(let a of Object.keys(o))if(!c.has(a))n.push({path:r?`${r}.${a}`:a,message:`Additional property '${a}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),c=this.validateWithRule(o,s,s.path);if(i.push(...c),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:zp},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Xu{fileLoader=new ca;envProcessor=new aa;validator=new Ju;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let a=this.checkCache(o.name||"",o);if(a)return a}let c;try{c=await this.loadConfigurationStrategies(o,!0,r)}catch(a){let l=o.__strictErrorHandling;if(a instanceof Error&&a.name==="ConfigNotFoundError"){if(l)throw a;c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(a instanceof Error&&a.name==="ConfigLoadError"){let u=a.message.includes("EACCES")||a.message.includes("EPERM")||a.message.includes("permission denied"),f=!u&&(a.message.includes("syntax")||a.message.includes("Expected")||a.message.includes("Unexpected")||a.message.includes("BuildMessage")||a.message.includes("errors building")),h=a.message.includes("Configuration must export a valid object")||a.message.includes("Configuration file is empty and exports nothing");if(l&&(h||u))throw a;if(f&&(!l||!h))c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${a.message}`]};else throw a}else c={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${a instanceof Error?a.message:String(a)}`]}}if(n||s)await this.validateConfiguration(c.config,n,s,o.name);if(r?.enabled&&c)this.cacheResult(o.name||"",c,r,o);if(i?.enabled){let a={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(a);if(i.slowThreshold&&a.duration>i.slowThreshold)Tt.warn(`Slow configuration loading detected: ${a.duration}ms for ${o.name}`);c.metrics=a}return c}catch(c){let a=Date.now()-t;throw Tt.error(`Configuration loading failed after ${a}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:c,checkEnv:a=!0,arrayStrategy:l="replace",verbose:u=!1}=e,f=s||Lr.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,f,o,c,l,u,a,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,f,o)),this.finalizeResult(d,h,a,i,u);let y=await this.loadHomeConfiguration(i,n,c,l,u,a);if(y)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(y,h,a,i,u);let g=await this.loadPackageJsonConfiguration(i,n,f,c,l,u,a);if(g)return h.push(qe(f,"package.json")),this.finalizeResult(g,h,a,i,u);if(h.push(...this.getAllSearchPaths(i,n,f,o)),t)throw gr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,c,a,u),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,c,a){let l=c?fn(e,n,o):n,u=this.getLocalDirectories(r,i);for(let f of u){if(o)Tt.info(`Searching for configuration in: ${f}`);let h=this.fileLoader.generateConfigPaths(e,f,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:a?.ttl,useCache:!a?.ttl||a.ttl>100});if(d){if(o)Tt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?fn(e,r,n):r,c=[qe(Si(),".config",e),qe(Si(),".config"),Si()];for(let a of c){if(n)Tt.info(`Checking home directory: ${a}`);let l=this.fileLoader.generateConfigPaths(e,a,t),u=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(u){if(n)Tt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let c=o?fn(e,i,s):i;try{let a=qe(r,"package.json");if(!Fu(a))return null;let l=await import(a),u=l[e],f=e;if(!u&&t)u=l[t],f=t;if(u&&typeof u==="object"&&!Array.isArray(u)){if(s)Tt.success(`Configuration loaded from package.json: ${f}`);return{config:qu(c,u,n),source:{type:"package.json",path:a,priority:30,timestamp:new Date}}}}catch(a){if(s)Tt.warn("Failed to load package.json:",[a instanceof Error?a:Error(String(a))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:fn(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw gr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Fi.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Fi.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(e,t){return Array.from(new Set([e,qe(e,"config"),qe(e,".config"),t?qe(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(qe(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[qe(Si(),".config",e),qe(Si(),".config"),Si()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function fp(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||i}async function cE(e){return er.loadConfig({...e,__strictErrorHandling:!0})}async function Up(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await er.loadConfig(e);else i=await er.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Tt.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let c=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await er.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function lE(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await er.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&fp(r)))return(await er.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await er.loadConfig({...e,cwd:e.cwd||Lr.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&fp(t)))return(await er.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function uE(e,t,r="replace"){let i=new ca;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function fn(e,t,r=!1){let i=new aa,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,c=[]){let a={...o};for(let[l,u]of Object.entries(o)){let f=[...c,l],h=[`${n}_${f.join("_").toUpperCase()}`,`${n}_${f.map((g)=>g.toUpperCase()).join("")}`,`${n}_${f.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,y;for(let g of h)if(d=Lr.env[g],d!==void 0){y=g;break}if(d!==void 0&&y)if(typeof u==="boolean")a[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof u==="number"){let g=Number(d);if(!Number.isNaN(g))a[l]=g}else if(Array.isArray(u))try{a[l]=JSON.parse(d)}catch{a[l]=d.split(",").map((g)=>g.trim())}else a[l]=d;else if(u&&typeof u==="object"&&!Array.isArray(u))a[l]=s(u,f)}return a}return s(t)}function fE(e){let t=qe(Lr.cwd(),e.configDir),r=qe(Lr.cwd(),e.generatedDir),i=qe(r,"config-types.ts");if(!Fu(qg(i)))g0(qg(i),{recursive:!0,mode:511});let n=Fu(t)?p0(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${jE}
|
|
162
|
+
export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
|
|
163
|
+
`;y0(i,s,{mode:438})}function hE(e){let t=null,r=null,i=()=>{if(!r)r=Up(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Tt.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let c=n[o];return i(),c},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,c){if(!t)t={...n};return t[o]=c,!0}})}function dE(e){let t=up(U0.cwd(),e?.configDir||"./config");function r(){if(!_0(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=j0(t).filter((a)=>n.has(Eu(a))).map((a)=>({base:a.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:a})),c=new Map;for(let{base:a,file:l}of o){let u=Eu(l).toLowerCase(),f=c.get(a);if(!f){c.set(a,l);continue}let h=Eu(f).toLowerCase();if(s.indexOf(u)<s.indexOf(h))c.set(a,l)}return Array.from(c.entries()).map(([a,l])=>({base:a,file:l})).sort((a,l)=>a.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",c=n.length?`{
|
|
164
|
+
${n.map((l)=>{let u=up(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${u}').default`}).join(`,
|
|
165
165
|
`)}
|
|
166
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
167
|
-
export type ConfigByName = ${
|
|
166
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${o}
|
|
167
|
+
export type ConfigByName = ${c}
|
|
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 Eq(){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 Eq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:x1.pid,hostname:$(),environment:x1.env.NODE_ENV||"development",platform:x1.platform,version:x1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:x1.env.NODE_ENV||x1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...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 fq(this.config.logDirectory,h9.F_OK|h9.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=_9(this.currentLogFile,"a",420),zq(X,W,{flag:"a"}),S9(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 z=Q;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let f=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{kW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let z=W,f=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let Q=j*2**(J-1);await new Promise((z)=>setTimeout(z,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 D1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return D1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return D1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(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 z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),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(D1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=O9(w),A=Qq($),X=x9();await Fq(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=_9(this.currentLogFile,"r+");S9(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(D1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.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 z=j(Q).trim().length,f=j($).length,B=Math.max(1,W-2-z-f);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("../"))$=Kq($);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 f=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:f,tag:B,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
|
|
171
|
-
`);for(let
|
|
172
|
-
`;if(
|
|
173
|
-
`;if(
|
|
174
|
-
`);if(this[
|
|
175
|
-
`,
|
|
176
|
-
`),
|
|
177
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
178
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
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=D1(this.config.logDirectory,A);if(w.before)try{if((await h1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var C7,V7=(w)=>w,O7=(w,$)=>{for(var Y in $)C7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:L7.bind($,Y)})},S7=(w,$)=>()=>(w&&($=w(w=0)),$),P9,p9,k1,KY,r9,SN,_N,T9,pX,vW,k0,w0,hN,N9,DN,q9,xN,kN,SW,ZN,H9,R9,_W,PN,iN,bN,uN,rX,t9,vN,Z0,cN,mN,M9,tX,cW,R0,v,gN,I9,dN,y9,nN,lN,hW,pN,C9,V9,rN,DW,tN,aN,sN,oN,eN,aX,a9,wq,$q="0.15.6",Aw,X8,BY,mW,gW,J8,dW,nW,GY,lW,pW,F$,s9,o9,Cw,w$,e9,w2,Yq,Uq,$2,W8,R3,C0,g,D3,Tq,x3,Nq,k3,Z3,k9,P3,qq,Hq,i3,Z9,b3,u3,v3,c3,m3,PW,Rq,g3;var A2=s(()=>{C7=Object.defineProperty;P9={};O7(P9,{withErrorRecovery:()=>c9,tryLoadConfig:()=>CN,loadConfigWithResult:()=>IN,loadConfig:()=>l9,isRetryableError:()=>TN,isConfigNotFoundError:()=>EN,isBunfigError:()=>m9,globalPerformanceMonitor:()=>KY,globalCache:()=>k1,getEnvOrDefault:()=>NN,generateConfigTypes:()=>VN,defaultGeneratedDir:()=>w2,defaultConfigDir:()=>e9,deepMergeWithArrayStrategy:()=>oW,deepMerge:()=>g9,createLibraryConfig:()=>LN,config:()=>yN,bunfigPlugin:()=>ON,applyEnvVarsToConfig:()=>zY,TypeGenerationError:()=>nW,SchemaValidationError:()=>GY,PluginError:()=>pW,PerformanceMonitor:()=>tW,FileSystemError:()=>dW,ErrorFactory:()=>F$,EnvVarError:()=>J8,EnvProcessor:()=>j8,ConfigValidator:()=>eW,ConfigValidationError:()=>mW,ConfigNotFoundError:()=>X8,ConfigMergeError:()=>gW,ConfigLoader:()=>wj,ConfigLoadError:()=>BY,ConfigFileLoader:()=>Q8,ConfigCache:()=>rW,CacheUtils:()=>r9,BunfigError:()=>Aw,BrowserConfigError:()=>lW,ArrayMergeStrategies:()=>s9});Yq=S7(async()=>{p9=import.meta.require,k1=new rW,KY=new tW,r9={createKey:AN,isEquivalent:XN,estimateMemoryUsage:JN},SN=eX(bW.cwd(),"config"),_N=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},vW=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,hN=k0.red,N9=k0.green,DN=k0.yellow,q9=k0.blue,xN=k0.magenta,kN=k0.cyan,SW=k0.white,ZN=k0.gray,H9=k0.bgRed,R9=k0.bgYellow,_W=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(SW(_W(" WARN "))),error:H9(SW(_W(" ERROR ")))},vN=new $8("stacks"),Z0=new $8("bunfig",{showTags:!0}),cN=p0(fY.cwd(),"config"),mN=p0(fY.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},cW=await KN(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=R0,gN=R0.red,I9=R0.green,dN=R0.yellow,y9=R0.blue,nN=R0.magenta,lN=R0.cyan,hW=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:y9("ℹ"),success:I9("✓"),warning:V9(hW(DW(" WARN "))),error:C9(hW(DW(" ERROR ")))},wq=new A8("stacks"),Aw=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 Aw{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 Aw{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 Aw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},gW=class extends Aw{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 Aw{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 Aw{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 Aw{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 Aw{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 Aw{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 Aw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},F$={configNotFound(w,$,Y){return new 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?:\/\//,Cw=new A8("bunfig",{showTags:!0}),w$=new wj,e9=r0(P$.cwd(),"config"),w2=r0(P$.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},R3=(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,D3=C0.red,Tq=C0.green,x3=C0.yellow,Nq=C0.blue,k3=C0.magenta,Z3=C0.cyan,k9=C0.white,P3=C0.gray,qq=C0.bgRed,Hq=C0.bgYellow,i3=C0.bgGray,Z9=C0.bold,b3=C0.dim,u3=C0.italic,v3=C0.underline,c3=C0.strikethrough,m3=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 ")))};g3=new FY("stacks")});var Z1={};ej(Z1,{shouldReusePort:()=>TY,safeStringify:()=>$$,safeDeleteFile:()=>Aj,resolvePathRewrite:()=>Yj,redactSensitive:()=>f8,isValidRootCA:()=>$j,isSingleProxyOptions:()=>NY,isSingleProxyConfig:()=>Oq,isProcessElevated:()=>EY,isMultiProxyOptions:()=>i$,isMultiProxyConfig:()=>G8,getSudoPassword:()=>E$,getPrimaryDomain:()=>B8,extractHostname:()=>Lq,execSudoSync:()=>T$,debugLog:()=>K,authorizeSystemAccess:()=>Iq});import{execSync as z8}from"node:child_process";import*as J2 from"node:fs/promises";function E$(){return process.env.SUDO_PASSWORD}function EY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function Iq(w={}){if(process.platform==="win32")return!0;if(EY()||!!E$())return!0;let $=w.exec??z8;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(EY())return z8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=E$(),Y=w.replace(/'/g,"'\\''");if($)return z8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return z8(`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 K(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 yq.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function f8(w){if(Array.isArray(w))return w.map((Y)=>f8(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]=f8(A)}return $}function $$(w,$){return JSON.stringify(f8(w),null,$)}function Lq(w){if(i$(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(i$(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 i$(w){return"proxies"in w&&Array.isArray(w.proxies)}function NY(w){return"to"in w&&typeof w.to==="string"}function Oq(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),K("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")K("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var Mq,X2="[redacted]",yq,Cq;var f0=s(()=>{A2();Mq=new FY("rpx",{showTags:!1});yq=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Cq=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as K8}from"node:child_process";import{homedir as Sq}from"node:os";import{join as _q}from"node:path";function F8(){return _q(Sq(),"Library/Keychains/login.keychain-db")}function Jj(){return[q$,F8()]}function U2(w,$=Xj){let Y=K8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
|
|
180
|
-
`)){let
|
|
181
|
-
`))if(
|
|
170
|
+
`}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}function HE(e,t={}){let r=sa.cwd();while(r.includes("storage"))r=xp(r,"..");let i=xp(r,e||"");if(t?.relative)return KE(sa.cwd(),i);return i}function Ce(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tT(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zt<"u"){let e=Zt.type;if(e==="renderer"||e==="worker")return!1;return!!(Zt.versions&&(Zt.versions.node||Zt.versions.bun))}return!1}class Xp{async format(e){let t=await tT(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Di.pid,hostname:t(),environment:Di.env.NODE_ENV||"development",platform:Di.platform,version:Di.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Di.env.NODE_ENV||Di.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class pn{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(e,t={}){this.name=e,this.config={...oa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Xp,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Du,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Du};return{...Du,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:oa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Ce()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,c=1000;while(s<o)try{try{try{await JE(this.config.logDirectory,Tp.F_OK|Tp.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await XE(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Jt.from(e);try{if(!Wo(this.currentLogFile))await Nu(this.currentLogFile,"",{mode:420});if(n=Ep(this.currentLogFile,"a",420),qE(n,a,{flag:"a"}),Sp(n),n!==void 0)Ou(n),n=void 0;if((await Oi(this.currentLogFile)).size===0){if(await Nu(this.currentLogFile,a,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let u=l;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(s<o-1){let f=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,f);let h=c*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(n!==void 0)try{Ou(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(a){if(s===o-1){let u=a,f=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}s++;let l=c*2**(s-1);await new Promise((u)=>setTimeout(u,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Ni(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 Ni(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Ce())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,a])=>a.createdAt.getTime()-c.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[c]of n.slice(o))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ku(16).toString("hex")}generateKey(){return ku(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=ku(16),i=YE("aes-256-gcm",t,r),n=Jt.isBuffer(e)?e:Jt.from(e,"utf8"),s=i.update(n),o=i.final(),c=s.length+o.length,a=i.getAuthTag(),l=Jt.allocUnsafe(16+c+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),a.copy(l,16+c),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Rp(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Jt.from(Jt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Ce())return;if(!this.shouldWriteToFile())return;let e=await Oi(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ko(this.config.logDirectory),s=n.filter((a)=>a.startsWith(this.name)&&/\.log\.\d+$/.test(a)).sort((a,l)=>{let u=Number.parseInt(a.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${o}`;if(await Oi(r).catch(()=>null))try{if(await Pp(r,c),t.compress)try{let a=`${c}.gz`;await this.compressLogFile(c,a),await Ho(c)}catch(a){console.error("Error compressing rotated file:",a)}if(s.length===0&&!n.some((a)=>a.endsWith(".log.1")))try{let a=`${r}.1`;await Nu(a,"")}catch(a){console.error("Error creating backup file:",a)}}catch(a){console.error(`Error during rotation: ${a instanceof Error?a.message:String(a)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Oi(r).catch(()=>null))await Pp(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Ko(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,c)=>c.localeCompare(o));for(let o of s.slice(t.maxFiles))await Ho(Ni(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Cp(e),i=GE(t),n=Rp();await eT(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Wo(this.currentLogFile))try{let e=Ep(this.currentLogFile,"r+");Sp(e),Ou(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Ce()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ko(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Ho(Ni(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?V.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Ce())return!1;let e=typeof M.env.NO_COLOR<"u",t=M.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,c=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let a=M.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${V.cyan(n)}`;if(!o)return l.trim();let u=c(l).trim().length,f=c(t).length,h=Math.max(1,a-2-u-f);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let c=Number.parseInt(o,10);return c<t[0].length?String(t[0][c]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let c=t[i++];switch(o){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=V.underline(V.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(o)}`,a="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${c}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>V.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>V.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>V.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>V.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>V.strikethrough(i)),t}supportsHyperlinks(){if(Ce())return!1;let e=M.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=M.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(QE(t)||t.startsWith("./")||t.startsWith("../"))t=ZE(t);else return null;return Wo(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,c;if(t instanceof Error)o=t.message,c=t.stack;else o=this.formatMessage(t,r);let{consoleText:a,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":oT[e],h=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:V.gray(a),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:V.green(a),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:f,tag:h,message:a,level:e}),console.error(d),c){let y=c.split(`
|
|
171
|
+
`);for(let g of y)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:V.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!Ce()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),c)console.error(c)}let u=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
|
|
172
|
+
`;if(c)u+=`${c}
|
|
173
|
+
`;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(e,t=""){let r={update:(c,a)=>{},finish:(c)=>{},interrupt:(c,a)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,a)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),a!==void 0)this.activeProgressBar.message=a;if(this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,a="info")=>{if(!Ce()&&M.stdout.isTTY)M.stdout.write(`
|
|
174
|
+
`);if(this[a==="warning"?"warn":a](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Ce()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":V.blue("◐"),tag:r,message:`${V.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,c=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
175
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":V.green("✓"),tag:u,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Ce())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new pn(t,{...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(r),r}createReadStream(){if(Ce())throw Error("createReadStream is not supported in browser environments");if(!Wo(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Cp(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let i=Jt.isBuffer(e)?e:Jt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),c=zE("aes-256-gcm",r,n);c.setAuthTag(s);let a=c.update(o),l=c.final(),u=a.length+l.length,f=Jt.allocUnsafe(u);return a.copy(f,0),l.copy(f,a.length),f.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Ce()}isServerMode(){return!Ce()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,t)}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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let c=n.split(`
|
|
176
|
+
`),a=Math.max(...c.map((h)=>h.length))+2,l=`┌${"─".repeat(a)}┐`,u=`└${"─".repeat(a)}┘`,f=c.map((h)=>this.formatConsoleMessage({timestamp:r,message:V.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(l),showTimestamp:!1})),f.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(u),showTimestamp:!1}))}else if(!Ce())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
|
|
177
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(Ce())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${V.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();M.stdin.removeListener("data",r);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let a=/%([sdijfo%])/g,l=0;if(r=e.replace(a,(u,f)=>{if(f==="%")return"%";if(l>=t.length)return u;let h=t[l++];switch(f){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return u}}),l<t.length)r+=` ${t.slice(l).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${V.blue("◐")} `;console.error(`${l}${a} ${V.cyan(i)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
178
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=V.green("━".repeat(i)),o=V.gray("━".repeat(n)),c=`[${s}${o}]`,a=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",u=this.options.showIcons===!1?"":t||r===100?V.green("✓"):V.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",h=`\r${u}${f} ${c} ${a}${l}`,d=M.stdout.columns||80,y=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${y}`,M.stdout.write(e.lastRenderedLine),t)M.stdout.write(`
|
|
179
|
+
`)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Ce()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Ce()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ko(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Ni(this.config.logDirectory,i);if(e.before)try{if((await Oi(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let i of r)try{await Ho(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var u0,f0=(e)=>e,d0=(e,t)=>{for(var r in t)u0(e,r,{get:t[r],enumerable:!0,configurable:!0,set:h0.bind(t,r)})},m0=(e,t)=>()=>(e&&(t=e(e=0)),t),Op,Wp,Fi,gn,Kp,mE,gE,hp,Yo,Mu,Be,te,pE,dp,yE,mp,wE,vE,Tu,bE,gp,pp,Pu,$E,xE,CE,SE,zo,Hp,EE,Le,TE,PE,yp,Go,Iu,xe,U,RE,wp,AE,vp,kE,OE,Ru,NE,bp,$p,DE,Au,FE,BE,LE,ME,IE,qo,Vp,_E,jE="0.15.6",nt,ia,dn,_u,ju,na,Uu,Wu,mn,Ku,Hu,gr,Yp,zp,Tt,er,Gp,qp,UE,VE,Jp,oa,cF,Te,V,vF,rT,bF,iT,$F,xF,Ap,CF,nT,sT,SF,kp,EF,TF,PF,RF,AF,Du,oT,kF;var Qp=Q(()=>{u0=Object.defineProperty;Op={};d0(Op,{withErrorRecovery:()=>Lp,tryLoadConfig:()=>uE,loadConfigWithResult:()=>cE,loadConfig:()=>Up,isRetryableError:()=>rE,isConfigNotFoundError:()=>tE,isBunfigError:()=>Mp,globalPerformanceMonitor:()=>gn,globalCache:()=>Fi,getEnvOrDefault:()=>iE,generateConfigTypes:()=>fE,defaultGeneratedDir:()=>qp,defaultConfigDir:()=>Gp,deepMergeWithArrayStrategy:()=>qu,deepMerge:()=>Ip,createLibraryConfig:()=>hE,config:()=>lE,bunfigPlugin:()=>dE,applyEnvVarsToConfig:()=>fn,TypeGenerationError:()=>Wu,SchemaValidationError:()=>mn,PluginError:()=>Hu,PerformanceMonitor:()=>Yu,FileSystemError:()=>Uu,ErrorFactory:()=>gr,EnvVarError:()=>na,EnvProcessor:()=>aa,ConfigValidator:()=>Ju,ConfigValidationError:()=>_u,ConfigNotFoundError:()=>ia,ConfigMergeError:()=>ju,ConfigLoader:()=>Xu,ConfigLoadError:()=>dn,ConfigFileLoader:()=>ca,ConfigCache:()=>Vu,CacheUtils:()=>Kp,BunfigError:()=>nt,BrowserConfigError:()=>Ku,ArrayMergeStrategies:()=>Yp});UE=m0(async()=>{Wp=import.meta.require,Fi=new Vu,gn=new Yu,Kp={createKey:W0,isEquivalent:K0,estimateMemoryUsage:H0},mE=Qo(Bu.cwd(),"config"),gE=Qo(Bu.cwd(),"src/generated"),hp=Xo.env.CLARITY_LOG_DIR||b0(z0(),"logs"),Yo={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hp,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Mu=await G0(),Be={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},te=Be,pE=Be.red,dp=Be.green,yE=Be.yellow,mp=Be.blue,wE=Be.magenta,vE=Be.cyan,Tu=Be.white,bE=Be.gray,gp=Be.bgRed,pp=Be.bgYellow,Pu=Be.bold,$E=Be.dim,xE=Be.italic,CE=Be.underline,SE=Be.reset,zo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hp={debug:"\uD83D\uDD0D",info:mp("ℹ"),success:dp("✓"),warning:pp(Tu(Pu(" WARN "))),error:gp(Tu(Pu(" ERROR ")))},EE=new ea("stacks"),Le=new ea("bunfig",{showTags:!0}),TE=Ge(hn.cwd(),"config"),PE=Ge(hn.cwd(),"src/generated"),yp=Jo.env.CLARITY_LOG_DIR||w0(Q0(),"logs"),Go={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yp,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Iu=await Z0(),xe={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},U=xe,RE=xe.red,wp=xe.green,AE=xe.yellow,vp=xe.blue,kE=xe.magenta,OE=xe.cyan,Ru=xe.white,NE=xe.gray,bp=xe.bgRed,$p=xe.bgYellow,DE=xe.bgGray,Au=xe.bold,FE=xe.dim,BE=xe.italic,LE=xe.underline,ME=xe.strikethrough,IE=xe.reset,qo={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vp={debug:"\uD83D\uDD0D",info:vp("ℹ"),success:wp("✓"),warning:$p(Ru(Au(" WARN "))),error:bp(Ru(Au(" ERROR ")))},_E=new ra("stacks"),nt=class extends Error{timestamp;context;constructor(t,r={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,i])=>`${r}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},ia=class extends nt{code="CONFIG_NOT_FOUND";constructor(t,r,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:i,searchPaths:r,searchPathCount:r.length})}},dn=class extends nt{code="CONFIG_LOAD_ERROR";constructor(t,r,i){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},_u=class extends nt{code="CONFIG_VALIDATION_ERROR";constructor(t,r,i){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:i,validationErrors:r,errorCount:r.length})}},ju=class extends nt{code="CONFIG_MERGE_ERROR";constructor(t,r,i,n){super(`Failed to merge configuration from "${t}" with "${r}": ${i.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},na=class extends nt{code="ENV_VAR_ERROR";constructor(t,r,i,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${i}`,{envKey:t,envValue:r,expectedType:i,configName:n})}},Uu=class extends nt{code="FILE_SYSTEM_ERROR";constructor(t,r,i){super(`File system ${t} failed for "${r}": ${i.message}`,{operation:t,path:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Wu=class extends nt{code="TYPE_GENERATION_ERROR";constructor(t,r,i){super(`Failed to generate types from "${t}" to "${r}": ${i.message}`,{configDir:t,outputPath:r,originalError:i.name,originalMessage:i.message});this.cause=i}},mn=class extends nt{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:t,configName:i,validationErrors:r,errorCount:r.length})}},Ku=class extends nt{code="BROWSER_CONFIG_ERROR";constructor(t,r,i,n){super(`Failed to fetch configuration from "${t}": ${r} ${i}`,{endpoint:t,status:r,statusText:i,configName:n})}},Hu=class extends nt{code="PLUGIN_ERROR";constructor(t,r,i){super(`Plugin "${t}" failed during ${r}: ${i.message}`,{pluginName:t,operation:r,originalError:i.name,originalMessage:i.message});this.cause=i}},gr={configNotFound(e,t,r){return new ia(e,t,r)},configLoad(e,t,r){return new dn(e,t,r)},configValidation(e,t,r){return new _u(e,t,r)},configMerge(e,t,r,i){return new ju(e,t,r,i)},envVar(e,t,r,i){return new na(e,t,r,i)},fileSystem(e,t,r){return new Uu(e,t,r)},typeGeneration(e,t,r){return new Wu(e,t,r)},schemaValidation(e,t,r){return new mn(e,t,r)},browserConfig(e,t,r,i){return new Ku(e,t,r,i)},plugin(e,t,r){return new Hu(e,t,r)}},Yp={replace:"replace",concat:"concat",smart:"smart"},zp=/^https?:\/\//,Tt=new ra("bunfig",{showTags:!0}),er=new Xu,Gp=qe(Lr.cwd(),"config"),qp=qe(Lr.cwd(),"src/generated")});VE=sa.env.CLARITY_LOG_DIR||WE(HE(),"logs"),Jp={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:VE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},oa={...Jp},cF=(async()=>{try{let{loadConfig:e}=await UE().then(()=>Op),t=await e({name:"clarity",alias:"logging",defaultConfig:Jp,cwd:sa.cwd()});if(t)Object.assign(oa,t)}catch{}return oa})();Te={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},V=Te,vF=Te.red,rT=Te.green,bF=Te.yellow,iT=Te.blue,$F=Te.magenta,xF=Te.cyan,Ap=Te.white,CF=Te.gray,nT=Te.bgRed,sT=Te.bgYellow,SF=Te.bgGray,kp=Te.bold,EF=Te.dim,TF=Te.italic,PF=Te.underline,RF=Te.strikethrough,AF=Te.reset,Du={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oT={debug:"\uD83D\uDD0D",info:iT("ℹ"),success:rT("✓"),warning:sT(Ap(kp(" WARN "))),error:nT(Ap(kp(" ERROR ")))};kF=new pn("stacks")});var Bi={};Qf(Bi,{authorizeSystemAccess:()=>cT,debugLog:()=>m,execSudoSync:()=>yr,extractHostname:()=>hT,getPrimaryDomain:()=>fa,getSudoPassword:()=>pr,isMultiProxyConfig:()=>ha,isMultiProxyOptions:()=>Mr,isProcessElevated:()=>yn,isSingleProxyConfig:()=>dT,isSingleProxyOptions:()=>vn,isValidRootCA:()=>Qu,redactSensitive:()=>ua,resolvePathRewrite:()=>Zu,safeDeleteFile:()=>ef,safeStringify:()=>tr,shouldReusePort:()=>wn});import{execSync as la}from"node:child_process";import*as ey from"node:fs/promises";function pr(){return process.env.SUDO_PASSWORD}function yn(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function cT(e={}){if(process.platform==="win32")return!0;if(yn()||!!pr())return!0;let t=e.exec??la;try{return t("sudo -n true",{stdio:"ignore"}),!0}catch{if(!e.interactive)return!1}try{return t("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function yr(e){if(yn())return la(e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let t=pr(),r=e.replace(/'/g,"'\\''");if(t)return la(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return la(`sudo -n sh -c '${r}'`,{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 m(e,t,r){if(r)aT.debug(`[rpx:${e}] ${t}`)}function wn(){let e=process.env.RPX_REUSE_PORT;return e==="1"||e==="true"}function fT(e){let t=e.toLowerCase();return lT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function ua(e){if(Array.isArray(e))return e.map((r)=>ua(r));if(typeof e==="string")return uT.test(e)?Zp:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,i]of Object.entries(e)){if(fT(r)){t[r]=Zp;continue}t[r]=ua(i)}return t}function tr(e,t){return JSON.stringify(ua(e),null,t)}function hT(e){if(Mr(e))return e.proxies.map((t)=>{let r=t.to||"stacks.localhost";return r.startsWith("http")?new URL(r).hostname:r});if(vn(e)){let t=e.to||"stacks.localhost";return[t.startsWith("http")?new URL(t).hostname:t]}return["stacks.localhost"]}function Qu(e){return typeof e==="object"&&e!==null&&"certificate"in e&&"privateKey"in e&&typeof e.certificate==="string"&&typeof e.privateKey==="string"}function fa(e){if(!e)return"stacks.localhost";if(Mr(e)&&e.proxies.length>0)return e.proxies[0].to||"stacks.localhost";if(vn(e))return e.to||"stacks.localhost";return"stacks.localhost"}function ha(e){return!!(e&&("proxies"in e)&&Array.isArray(e.proxies))}function Mr(e){return"proxies"in e&&Array.isArray(e.proxies)}function vn(e){return"to"in e&&typeof e.to==="string"}function dT(e){return!!(e&&("to"in e)&&!("proxies"in e))}function Zu(e,t){if(!t||t.length===0)return null;for(let r of t)if(e===r.from||e.startsWith(`${r.from}/`)){let i=r.to.startsWith("http")?new URL(r.to).host:r.to,n=r.stripPrefix===!0?e.slice(r.from.length)||"/":e;return{targetHost:i,targetPath:n}}return null}async function ef(e,t){try{await ey.unlink(e),m("certificates",`Successfully deleted: ${e}`,t)}catch(r){if(r.code!=="ENOENT")m("certificates",`Warning: Could not delete ${e}: ${r}`,t)}}var aT,Zp="[redacted]",lT,uT;var he=Q(()=>{Qp();aT=new pn("rpx",{showTags:!1});lT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),uT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as da}from"node:child_process";import{homedir as mT}from"node:os";import{join as gT}from"node:path";function ma(){return gT(mT(),"Library/Keychains/login.keychain-db")}function rf(){return[vr,ma()]}function ty(e,t=tf){let r=da(`security find-certificate -a -c "${t}" -Z "${e}" 2>/dev/null || true`,{encoding:"utf8"}),i=[];for(let n of r.split(`
|
|
180
|
+
`)){let s=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(s)i.push(s[1].toUpperCase())}return i}function nf(e){if(process.platform!=="darwin")return;let t=Br(e.caPath);if(!t)return;let r=e.commonName??tf,i=e.keychains??rf();for(let n of i)for(let s of ty(n,r)){if(s===t)continue;try{if(n.startsWith("/Library"))yr(`security delete-certificate -Z ${s} "${n}"`);else da(`security delete-certificate -Z ${s} "${n}"`,{stdio:"ignore"});m("ssl",`Removed stale Root CA ${s} from ${n}`,e.verbose)}catch{}}}function sf(e,t,r){if(process.platform!=="darwin")return ga(e,r);try{let n=da(`security verify-cert -c "${e}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return m("ssl",`verify-cert ${t}: ${n?"trusted":"not trusted"}`,r?.verbose),n}catch{return!1}}function ga(e,t){let r=Br(e);if(!r)return!1;for(let i of rf())try{let n=da(`security find-certificate -a -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"});for(let s of n.split(`
|
|
181
|
+
`))if(s.toUpperCase().includes("SHA-256")){if(s.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${i}`,t?.verbose),!0}}catch{}return!1}var wr="-d -r trustRoot -p ssl -p basic",vr="/Library/Keychains/System.keychain",tf="rpx.localhost";var of=Q(()=>{Do();he()});import{execSync as af}from"node:child_process";import de from"node:fs/promises";import*as cf from"node:os";import{homedir as Li}from"node:os";import*as ny from"node:path";import{join as me}from"node:path";import*as br from"node:process";function sy(e,t){return[...new Set(e.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function oy(e,t,r){let i=me(Li(),".stacks","ssl"),n=[...new Set([t,...e,"rpx.localhost"])];return{https:{certPath:lf,keyPath:me(i,"rpx.localhost.key"),caCertPath:me(i,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:n.map((s)=>({from:"localhost:1",to:s,cleanUrls:!1}))}}function ay(e){return{caCertPath:me(e,yT),caKeyPath:me(e,wT)}}async function vT(e,t){try{let[r,i]=await Promise.all([de.readFile(e.caCertPath,"utf8"),de.readFile(e.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!i.includes("PRIVATE KEY-----"))return m("ssl",`Root CA files at ${e.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:i}}catch(r){return m("ssl",`No existing Root CA at ${e.caCertPath} (${r.code||r}), will create one`,t),null}}function ry(e){let t=new Set;t.add(e);let r=e.split(".");if(r.length>=3){let i=r[r.length-1],n=r[r.length-2],s=new Set(["co","com","org","net","ac","gov","edu"]);if(!(r.length===3&&i.length===2&&s.has(n)))t.add(`*.${r.slice(1).join(".")}`)}return Array.from(t)}function cy(e){let r=fa(e).replace(/\*/g,"wildcard"),i=me(Li(),".stacks","ssl"),n=i;if(typeof e?.https==="object")return n=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:i,{caCertPath:e.https.caCertPath||me(n,`${r}.ca.crt`),certPath:e.https.certPath||me(n,`${r}.crt`),keyPath:e.https.keyPath||me(n,`${r}.key`)};return{caCertPath:me(n,`${r}.ca.crt`),certPath:me(n,`${r}.crt`),keyPath:me(n,`${r}.key`)}}function iy(e){let t=new Set;if(Mr(e))e.proxies.forEach((r)=>{let i=r.to||"rpx.localhost";ry(i).forEach((n)=>t.add(n))});else if(vn(e)){let r=e.to||"rpx.localhost";ry(r).forEach((i)=>t.add(i))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function bn(e){if($r&&!e.forceRegenerate){m("ssl","Using cached SSL configuration",e.verbose);return}uf();let t=Mr(e)?e.proxies.map((u)=>u.to):[e.to];m("ssl",`Generating certificate for domains: ${t.join(", ")}`,e.verbose);let r=$n(e,e.verbose),i=r.basePath||me(Li(),".stacks","ssl");await de.mkdir(i,{recursive:!0});let n=ay(i),s=await vT(n,e.verbose),o=!1;if(!s){if(e.verbose)x.info("Generating Root CA certificate (one-time)...");s=await lu(r);try{await Promise.all([de.writeFile(n.caCertPath,s.certificate),de.writeFile(n.caKeyPath,s.privateKey,{mode:384})]),o=!0,m("ssl",`Persisted Root CA at ${n.caCertPath}`,e.verbose)}catch(u){throw m("ssl",`Error saving Root CA files: ${u}`,e.verbose),Error(`Failed to save Root CA files: ${u}`)}}else m("ssl",`Reusing existing Root CA from ${n.caCertPath}`,e.verbose);if(e.verbose)x.info(`Generating host certificate for: ${t.join(", ")}`);let c=await uu({...r,rootCA:{certificate:s.certificate,privateKey:s.privateKey}});try{await Promise.all([de.writeFile(r.certPath,c.certificate),de.writeFile(r.keyPath,c.privateKey),de.writeFile(r.caCertPath,s.certificate)]),m("ssl","Certificate files saved successfully",e.verbose)}catch(u){throw m("ssl",`Error saving certificate files: ${u}`,e.verbose),Error(`Failed to save certificate files: ${u}`)}if(o?!1:await uy(n.caCertPath,{verbose:e.verbose,regenerateUntrustedCerts:!0})){if(m("ssl","Root CA already trusted, skipping trust store update",e.verbose),e.verbose)x.success("Root CA is already trusted in system trust store");if($r={key:c.privateKey,cert:c.certificate,ca:s.certificate},e.verbose)x.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(e.verbose)x.info("Adding certificate to system trust store (may require sudo permission)...");let l=!1;if(br.platform==="darwin")try{nf({caPath:n.caCertPath,verbose:e.verbose});let u=ma();try{af(`security add-trusted-cert ${wr} -k "${u}" "${n.caCertPath}"`,{stdio:"ignore"})}catch{}if(yr(`security add-trusted-cert ${wr} -k ${vr} "${n.caCertPath}"`),e.verbose)x.success("Successfully added Root CA to system trust store");l=!0;let f=me(i,"trust-rpx-cert.sh"),h=`#!/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 ${wr} -k ${vr} "${n.caCertPath}"
|
|
189
189
|
else
|
|
190
|
-
sudo security add-trusted-cert ${
|
|
190
|
+
sudo security add-trusted-cert ${wr} -k ${vr} "${n.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."
|
|
194
|
-
`;await
|
|
194
|
+
`;await de.writeFile(f,h,{mode:493})}catch(u){if(e.verbose)x.warn(`Could not add Root CA to trust store automatically: ${u}`);let f=me(i,"trust-rpx-cert.sh"),h=`#!/bin/bash
|
|
195
195
|
echo "Trusting RPX Root CA"
|
|
196
196
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
197
197
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
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 ${wr} -k ${vr} "${n.caCertPath}"
|
|
202
202
|
else
|
|
203
|
-
sudo security add-trusted-cert ${
|
|
203
|
+
sudo security add-trusted-cert ${wr} -k ${vr} "${n.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."
|
|
207
|
-
`;if(await
|
|
207
|
+
`;if(await de.writeFile(f,h,{mode:493}),e.verbose)x.info(`Created a trust helper script at: ${f}`),x.info(`If you're still having certificate issues, run: sh ${f}`)}else if(br.platform==="linux")try{let{exec:u}=await import("node:child_process"),f="/usr/local/share/ca-certificates/rpx",h=`
|
|
208
208
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
209
|
-
cp "${
|
|
209
|
+
cp "${n.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
210
210
|
update-ca-certificates
|
|
211
211
|
echo "RPX Root CA installed. Please restart your browser."
|
|
212
|
-
`,
|
|
213
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${
|
|
212
|
+
`,d=me(cf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await de.writeFile(d,h,{mode:493}),await new Promise((y)=>{u(`sudo bash "${d}"`,(g)=>{if(g){if(e.verbose)x.warn(`Could not trust certificates: ${g}`);y(!1)}else{if(e.verbose)x.success("Successfully added certificates to system trust store");y(!0)}})}),await de.unlink(d).catch(()=>{}),l=!0}catch(u){if(e.verbose)x.warn(`Failed to trust certificates: ${u}`)}else if(br.platform==="win32")try{let u=`
|
|
213
|
+
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${n.caCertPath.replace(/\//g,"\\")}")
|
|
214
214
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
215
215
|
$store.Open("ReadWrite")
|
|
216
216
|
$store.Add($cert)
|
|
217
217
|
$store.Close()
|
|
218
218
|
Write-Host "Root CA trusted successfully!"
|
|
219
|
-
`,f=
|
|
220
|
-
`)){let
|
|
221
|
-
`),
|
|
222
|
-
`,
|
|
223
|
-
host: ${
|
|
224
|
-
x-forwarded-for:
|
|
219
|
+
`,f=me(cf.tmpdir(),"rpx-trust.ps1");if(await de.writeFile(f,u),af(`powershell -ExecutionPolicy Bypass -File "${f}"`),e.verbose)x.success("Successfully added certificate to Windows trust store");l=!0}catch(u){if(e.verbose)x.warn(`Could not trust certificate: ${u}`)}else try{await du(c,s.certificate,r),l=!0}catch(u){if(e.verbose)x.warn(`Could not add certificate to trust store: ${u}`)}if($r={key:c.privateKey,cert:c.certificate,ca:s.certificate},e.verbose)x.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!l&&e.verbose)x.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),x.warn("This will bypass the warning and you should only need to do it once")}function uf(){$r=null}async function xr(e){if(!e)return null;if($r)return $r;let t=$n(e);try{let[r,i,n]=await Promise.all([de.access(t.keyPath).then(()=>!0).catch(()=>!1),de.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?de.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!i)return m("ssl",`Certificate files don't exist: key=${r}, cert=${i}, paths: ${t.keyPath}, ${t.certPath}`,e.verbose),null;let s="regenerateUntrustedCerts"in e,o=e.regenerateUntrustedCerts,c=s?o!==!1:!0;m("ssl",`Trust check: hasFlag=${s}, flagValue=${o}, shouldCheckTrust=${c}`,e.verbose);let a=t.basePath||me(Li(),".stacks","ssl"),l=ay(a);if(!(c?await uy(l.caCertPath,e):!0))return m("ssl","Root CA exists but is not trusted, will regenerate",e.verbose),null;let[f,h,d]=await Promise.all([de.readFile(t.keyPath,"utf8"),de.readFile(t.certPath,"utf8"),n&&t.caCertPath?de.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(d&&!d.includes("-----BEGIN CERTIFICATE-----"))return m("ssl","Invalid root CA certificate content, will regenerate",e.verbose),null;if(Mr(e))try{let{X509Certificate:y}=await import("node:crypto"),p=new y(h).subjectAltName||"",b=e.proxies.map((P)=>P.to).filter((P)=>!p.includes(`DNS:${P}`));if(b.length>0)return m("ssl",`Certificate missing SANs for: ${b.join(", ")}, will regenerate`,e.verbose),null}catch(y){m("ssl",`Could not verify cert SANs: ${y}`,e.verbose)}return m("ssl","Successfully loaded existing certificates",e.verbose),$r={key:f,cert:h,ca:d},$r}catch(r){return m("ssl",`Error checking existing certificates: ${r}`,e.verbose),null}}function $n(e,t){let r=fa(e);m("ssl",`Primary domain: ${r}`,t);let i=cy(e),n=me(Li(),".stacks","ssl");if(typeof e.https==="object"){let s=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:n,o={domain:r,hostCertCN:r,basePath:s,caCertPath:e.https.caCertPath||i.caCertPath,certPath:e.https.certPath||i.certPath,keyPath:e.https.keyPath||i.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:e.https.commonName||r,organizationName:e.https.organizationName||"Local Development",countryName:e.https.countryName||"US",stateName:e.https.stateName||"California",localityName:e.https.localityName||"Playa Vista",validityDays:e.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(iy(e)).map((c)=>({type:2,value:c}))};if(Qu(e.https.rootCA))o.rootCA=e.https.rootCA;return o}return{domain:r,hostCertCN:r,basePath:n,...i,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(iy(e)).map((s)=>({type:2,value:s}))}}async function ly(e,t){let r=cy({to:e,verbose:t}),i=[r.caCertPath,r.certPath,r.keyPath];m("certificates","Attempting to clean up relating certificates",t),await Promise.all(i.map((n)=>ef(n,t)))}async function uy(e,t){try{if(m("ssl",`Checking if certificate is trusted: ${e}`,t?.verbose),br.platform==="darwin"){if(t?.serverName)return sf(e,t.serverName,{verbose:t?.verbose});return ga(e,{verbose:t?.verbose})}else if(br.platform==="win32")try{let r=mu(e)||"";if(!r)return m("ssl","Could not extract certificate subject",t?.verbose),!1;let i=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(af(i).toString().includes(r))return m("ssl","Certificate found in trusted root store",t?.verbose),!0;return m("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(br.platform==="linux")try{let r=Br(e);if(!r)return m("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let i=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let n of i){let s;try{s=await de.readdir(n)}catch{continue}for(let o of s){let c=Br(ny.join(n,o));if(c&&c===r)return m("ssl",`Certificate fingerprint found in ${n}`,t?.verbose),!0}}return m("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return m("ssl",`Platform ${br.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return m("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}var $r=null,lf,yT="rpx-root-ca.crt",wT="rpx-root-ca.key";var ff=Q(()=>{No();Nr();Ls();of();he();of();Do();Do();lf=me(Li(),".stacks","ssl","rpx.localhost.crt")});function bT(e){return{enabled:e?.enabled??!1,path:e?.path??"/",interval:e?.interval??1e4,timeout:e?.timeout??2000,healthyThreshold:e?.healthyThreshold??2,unhealthyThreshold:e?.unhealthyThreshold??3}}function $T(e){return(Array.isArray(e)?e:[e]).map((r)=>{let i=typeof r==="string"?{url:r}:r;return{url:i.url,weight:i.weight&&i.weight>0?i.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function fy(e){return(Array.isArray(e)?e:[e]).map((r)=>typeof r==="string"?r:r.url)}function Ir(e){if(!e)return"localhost:5173";let t=Array.isArray(e)?e[0]:e;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function xn(e,t){return{upstreams:$T(e),strategy:t?.strategy??"round-robin",healthCheck:bT(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function xT(e){let t=e.upstreams.filter((r)=>r.healthy);if(t.length===0&&e.upstreams.length===1)return e.upstreams;return t}function CT(e,t){let r=e.cursor%t.length;return e.cursor=(e.cursor+1)%t.length,t[r]}function ST(e,t){if(e.wrrCurrentWeights.length!==t.length)e.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((n,s)=>n+s.weight,0),i=0;for(let n=0;n<t.length;n++)if(e.wrrCurrentWeights[n]+=t[n].weight,e.wrrCurrentWeights[n]>e.wrrCurrentWeights[i])i=n;return e.wrrCurrentWeights[i]-=r,t[i]}function ET(e){let t=e[0];for(let r=1;r<e.length;r++)if(e[r].activeConnections<t.activeConnections)t=e[r];return t}function hy(e){let t=xT(e);if(t.length===0)return;if(t.length===1)return t[0];switch(e.strategy){case"weighted-round-robin":return ST(e,t);case"least-connections":return ET(t);case"round-robin":default:return CT(e,t)}}function pa(e,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=e.healthCheck.healthyThreshold)t.healthy=!0}function Cn(e,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=e.healthCheck.unhealthyThreshold)t.healthy=!1}function TT(e){let t=e.lastIndexOf(":");if(t===-1)return{hostname:e,port:80};let r=Number(e.slice(t+1));return{hostname:e.slice(0,t),port:Number.isFinite(r)?r:80}}async function PT(e,t){let{hostname:r,port:i}=TT(t.url),n=new AbortController,s=setTimeout(()=>n.abort(),e.healthCheck.timeout);try{(await fetch(`http://${r}:${i}${e.healthCheck.path}`,{signal:n.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),pa(e,t)}catch{Cn(e,t)}finally{clearTimeout(s)}}function Sn(e){if(!e.healthCheck.enabled||e.healthCheckTimer||e.upstreams.length<2)return;let t=setInterval(()=>{for(let r of e.upstreams)PT(e,r)},e.healthCheck.interval);t.unref?.(),e.healthCheckTimer=t}function Mi(e){if(e.healthCheckTimer)clearInterval(e.healthCheckTimer),e.healthCheckTimer=null}import{createHash as my,timingSafeEqual as dy}from"node:crypto";import{readFileSync as RT}from"node:fs";function En(e,t){let r=Buffer.from(e,"utf8"),i=Buffer.from(t,"utf8");if(r.length!==i.length)return dy(r,r),!1;return dy(r,i)}function kT(e,t){let r=(h)=>my("md5").update(h).digest(),i=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8"),s=r(Buffer.concat([i,n,i])),o=[i,Buffer.from("$apr1$","utf8"),n];for(let h=i.length;h>0;h-=16)o.push(s.subarray(0,Math.min(h,16)));for(let h=i.length;h>0;h>>=1)o.push(h&1?Buffer.from([0]):i.subarray(0,1));let c=r(Buffer.concat(o));for(let h=0;h<1000;h++){let d=[];if(d.push(h&1?i:c.subarray(0,16)),h%3)d.push(n);if(h%7)d.push(i);d.push(h&1?c.subarray(0,16):i),c=r(Buffer.concat(d))}let a="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",l=(h,d)=>{let y="",g=h;for(let p=0;p<d;p++)y+=a[g&63],g>>=6;return y},u=c,f="";return f+=l(u[0]<<16|u[6]<<8|u[12],4),f+=l(u[1]<<16|u[7]<<8|u[13],4),f+=l(u[2]<<16|u[8]<<8|u[14],4),f+=l(u[3]<<16|u[9]<<8|u[15],4),f+=l(u[4]<<16|u[10]<<8|u[5],4),f+=l(u[11],2),`$apr1$${t}$${f}`}function OT(e,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(e,t)}catch{return!1}if(t.startsWith("$apr1$")){let i=t.split("$")[2]??"";return En(kT(e,i),t)}if(t.startsWith("{SHA}")){let r=my("sha1").update(e,"utf8").digest("base64");return En(`{SHA}${r}`,t)}return En(e,t)}function NT(e){let t=new Map;for(let r of e.split(`
|
|
220
|
+
`)){let i=r.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf(":");if(n<=0)continue;t.set(i.slice(0,n),i.slice(n+1))}return t}function Tn(e){if(!e)return;let t=(e.realm??"").trim()||"Restricted",r=[];if(e.username)r.push({username:e.username,password:e.password??""});for(let s of e.users??[])if(s?.username)r.push({username:s.username,password:s.password??""});let i;if(e.htpasswdFile)try{i=NT(RT(e.htpasswdFile,"utf8"))}catch{i=void 0}if(r.length===0&&(!i||i.size===0))return;return{realm:t,verify:(s,o)=>{let c=!1;for(let a of r)if(En(s,a.username)&&En(o,a.password))c=!0;if(i){let a=i.get(s);if(a&&OT(o,a))c=!0}return c}}}function gy(e,t,r){if(t.startsWith(AT))return;let i=e.headers.get("authorization")??"",n=i.indexOf(" "),s=n===-1?i:i.slice(0,n),o=n===-1?"":i.slice(n+1).trim();if(s.toLowerCase()==="basic"&&o){let a="";try{a=Buffer.from(o,"base64").toString("utf8")}catch{a=""}let l=a.indexOf(":");if(l>=0&&r.verify(a.slice(0,l),a.slice(l+1)))return}let c=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${c}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var AT="/.well-known/acme-challenge/";var ya=()=>{};function BT(e){return FT.has(e.toUpperCase())}function LT(){let e=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(e)&&e>0?e:30000}function MT(e){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:e*8}function IT(){let e=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(e)&&e>0?e:0}function _T(){let e=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(e)&&e>0?e:0}function jT(){let e=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(e)&&e>0?e:256}class by{socket=null;buf=new Uint8Array(UT);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(e){let t=this.socket,r=t.write(e);while(r<e.length){if(this.closed)throw wa;await new Promise((i)=>{this.drainWaiter=i}),r+=t.write(e.subarray(r))}}wakeDrain(){let e=this.drainWaiter;if(e)this.drainWaiter=null,e()}push(e){if(this.bodyQueue){let t=e.length<=this.bodyRemaining?e.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(e.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<e.length)this.appendToBuf(e.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(e),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()>WT)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=KT)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(e){let t=this.len+e.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(e,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let e=this.waiter;if(e)this.waiter=null,e()}waitForData(e){if(this.len>e||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((e)=>{this.waiter=e})}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 $y{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=LT();maxWaiters;checkoutIdleMs=IT();inUse=new Set;constructor(e,t,r,i=""){this.host=e;this.port=t;this.maxTotal=r;this.key=i;this.maxWaiters=MT(r)}trackCheckout(e){if(e.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(e),this.ensureSweeper()}dial(){let e=new by;return DT({hostname:this.host,port:this.port,socket:{data:(t,r)=>e.push(r),drain:()=>e.wakeDrain(),close:()=>e.markClosed(),end:()=>e.markClosed(),error:()=>e.markClosed(),connectError:()=>e.markClosed(),timeout:()=>e.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let i=_T();if(i>0)r.timeout?.(i);return e.socket=t,e})}acquireIdleSync(){while(this.idle.length){let e=this.idle.pop();if(!e.closed)return e.socket?.ref(),e.pos=0,e.len=0,this.trackCheckout(e),e;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw _r;let e=await this.waitForSlot();if(e===_r)throw _r;if(e)return e.pos=0,e.len=0,this.trackCheckout(e),e}this.open++;try{let e=await this.dial();return this.trackCheckout(e),e}catch(e){throw this.open--,this.wakeWaiter(),e}}waitForSlot(){return new Promise((e)=>{let t=!1,r=(s)=>{if(t)return;t=!0,clearTimeout(n),e(s)},i=(s)=>r(s),n=setTimeout(()=>{let s=this.waiters.indexOf(i);if(s!==-1)this.waiters.splice(s,1);r(_r)},this.queueWaitMs);n.unref?.(),this.waiters.push(i)})}release(e){if(this.inUse.delete(e),e.closed){this.open--,this.wakeWaiter();return}e.clearStreaming(),e.compact(),e.fresh=!1;let t=this.waiters.shift();if(t){e.socket?.ref(),this.trackCheckout(e),t(e);return}e.idleSince=Date.now(),e.socket?.unref(),this.idle.push(e),this.ensureSweeper()}destroy(e){this.inUse.delete(e),e.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let e=this.waiters.shift();if(e)e(null)}ensureSweeper(){if(this.sweeper)return;let e=this.checkoutIdleMs>0?Math.min(hf,this.checkoutIdleMs):hf;this.sweeper=setInterval(()=>this.sweep(),e),this.sweeper.unref?.()}sweep(){let e=Date.now(),t=e-hf;if(this.idle.length){let r=[];for(let i of this.idle)if(i.closed||i.idleSince<=t)i.destroy(),this.open--;else r.push(i);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=e-this.checkoutIdleMs;for(let i of this.inUse)if(!i.closed&&i.lastActivityAt>0&&i.lastActivityAt<=r)i.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&va.get(this.key)===this)va.delete(this.key)}}}function GT(e,t){let r=va.get(e);if(!r){let i=e.lastIndexOf(":"),n=i===-1?e:e.slice(0,i),s=i===-1?80:Number(e.slice(i+1));r=new $y(n,s,t??jT(),e),va.set(e,r)}return r}function py(e,t,r){for(let i=r+3;i<t;i++)if(e[i]===10&&e[i-1]===13&&e[i-2]===10&&e[i-3]===13)return i-3;return-1}function qT(e,t,r){let i=vy.decode(e.subarray(t,r)),n=i.indexOf(`\r
|
|
221
|
+
`),s=n===-1?i:i.slice(0,n),o=s.indexOf(" "),c=Number.parseInt(s.slice(o+1,o+5),10),a=s.startsWith("HTTP/1.0"),l=[],u=-1,f=!1,h=a,d=!1,y=!1,g=n===-1?i.length:n+2;while(g<i.length){let p=i.indexOf(`\r
|
|
222
|
+
`,g);if(p===-1)p=i.length;let w=i.slice(g,p);if(g=p+2,w==="")continue;let b=w.indexOf(":");if(b===-1)continue;let P=w.slice(0,b),R=w.slice(b+1).trim(),v=P.charCodeAt(0)|32;if(v===99||v===116||v===107){let T=P.toLowerCase();if(T==="content-length"){let S=/^\d+$/.test(R)?Number(R):Number.NaN;if(!Number.isSafeInteger(S)||u>=0&&u!==S)y=!0;else u=S;continue}if(T==="transfer-encoding"){if(R.toLowerCase().includes("chunked"))f=!0;continue}if(T==="connection"){let S=R.toLowerCase();if(S.includes("close"))h=!0;if(S.includes("keep-alive"))d=!0;continue}if(T==="keep-alive")continue}l.push([P,R])}if(a&&d)h=!1;if(f&&u>=0)u=-1;return{status:c,headerEnd:r,headers:l,contentLength:u,chunked:f,closeConn:h,malformed:y}}function JT(e,t){return t||e===204||e===304}async function xy(e){let{hostPort:t,method:r,path:i,reqHeaders:n,forwardedHost:s,clientIp:o,originOverride:c,body:a}=e,l=r==="HEAD",u=n.get("accept")?.toLowerCase()??"";if(n.get("expect")||n.get("upgrade")||u.includes("text/event-stream"))throw Pn;let f=null;if(a){let g=n.get("content-length"),p=g?Number.parseInt(g,10):Number.NaN;if(Number.isNaN(p)||p>yy)throw Pn;if(f=await iP(a),f===null)throw Pn}let h=rP(r,i,n,t,s,o,c,f),d=h;if(f&&f.length)d=new Uint8Array(h.length+f.length),d.set(h),d.set(f,h.length);let y=GT(t,e.maxPerHost);for(let g=0;;g++){if(g>0)await new Promise((w)=>{setTimeout(w,g)});let p;try{p=y.acquireIdleSync()??await y.acquireOrDial()}catch(w){if(w!==_r&&g<4)continue;throw w}try{let w=p.socket.write(d);if(w<d.length)await p.writeAll(d.subarray(w));return await QT(y,p,l,e.signal)}catch(w){let b=w===wa&&g<4&&(p.fresh||BT(r));if(y.destroy(p),b)continue;if(w===wa)throw Error("upstream closed connection");throw w}}}async function XT(e){let t=py(e.buf,e.len,e.pos);while(t===-1){if(e.closed){if(e.timedOut)throw df;if(e.len===e.pos)throw wa;throw Error("upstream closed mid-header")}if(e.len-e.pos>wy)throw Error("upstream header block too large");await e.waitForData(e.len),t=py(e.buf,e.len,e.pos)}return t}async function QT(e,t,r,i){let n;for(;;){let o=await XT(t);if(n=qT(t.buf,t.pos,o),t.pos=o+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw e.destroy(t),Error("upstream sent malformed response framing");let s=n.headers;if(JT(n.status,r))return Cy(e,t,n.closeConn),new Response(null,{status:n.status,headers:s});if(n.chunked)return new Response(tP(e,t,n.closeConn,i),{status:n.status,headers:s});if(n.contentLength>=0){if(t.len-t.pos>=n.contentLength){let c=t.pos+n.contentLength,a=t.len>c,l=null;if(n.contentLength>=HT)l=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(VT);else if(n.contentLength>0)l=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,n.closeConn||a)e.destroy(t);else e.release(t);return new Response(l,{status:n.status,headers:s})}return new Response(ZT(e,t,n.contentLength,n.closeConn),{status:n.status,headers:s})}return new Response(eP(t),{status:n.status,headers:s})}function Cy(e,t,r){if(r||t.pos!==t.len)e.destroy(t);else e.release(t)}function ZT(e,t,r,i){let n=t.len-t.pos,s=n>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-n,t.queuedBytes=0,t.streamingBody=!0;let o=(c)=>{if(t.bodyQueue=null,i||t.len>0)e.destroy(t);else e.release(t);c.close()};return new ReadableStream({start(c){if(s)c.enqueue(s);if(t.bodyRemaining===0&&t.bodyQueue.length===0)o(c)},async pull(c){for(;;){let a=t.bodyQueue;if(a&&a.length>0){let l=a.shift();if(t.queuedBytes-=l.length,t.resumeIfDrained(),c.enqueue(l),t.bodyRemaining===0&&a.length===0)o(c);return}if(t.bodyRemaining===0){if(t.bodyQueue)o(c);return}if(t.closed){t.bodyQueue=null,e.destroy(t),c.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,e.destroy(t)}})}function eP(e){return e.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(e.len>e.pos){t.enqueue(e.buf.slice(e.pos,e.len)),e.pos=e.len,e.resumeIfDrained();return}if(e.closed){e.destroy(),t.close();return}await e.waitForData(e.len)}},cancel(){e.destroy()}})}function tP(e,t,r,i){t.streamingBody=!0;let n=0,s=!1,o=!1,c,a=()=>i?.removeEventListener("abort",l),l=()=>{if(o)return;o=!0,e.destroy(t);try{c?.close()}catch{}};async function u(f=!1){for(;;){for(let h=t.pos;h+1<t.len;h++)if(t.buf[h]===13&&t.buf[h+1]===10){let d=vy.decode(t.buf.subarray(t.pos,h));return t.pos=h+2,d}if(t.closed){if(f&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>wy)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start(f){if(c=f,i?.aborted)l();else i?.addEventListener("abort",l,{once:!0})},async pull(f){try{for(;;){if(n>0){if(t.len===t.pos){if(t.closed){e.destroy(t),f.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let g=Math.min(n,t.len-t.pos);if(f.enqueue(t.buf.slice(t.pos,t.pos+g)),t.pos+=g,n-=g,t.resumeIfDrained(),n===0)s=!0;return}if(s)await u(),s=!1;let h=await u(!0);if(h===null){e.destroy(t),a(),f.close();return}let d=h.indexOf(";"),y=Number.parseInt(d===-1?h:h.slice(0,d),16);if(!Number.isInteger(y)||y<0){e.destroy(t),f.error(Error("upstream sent malformed chunk size"));return}if(y===0){for(;;)if(await u()==="")break;Cy(e,t,r),a(),f.close();return}n=y}}catch(h){if(e.destroy(t),a(),!o)f.error(h)}},cancel(){o=!0,a(),e.destroy(t)}})}function rP(e,t,r,i,n,s,o,c){let a=s||"127.0.0.1",l=`${e} ${t} HTTP/1.1\r
|
|
223
|
+
host: ${i}\r
|
|
224
|
+
x-forwarded-for: ${a}\r
|
|
225
|
+
x-real-ip: ${a}\r
|
|
225
226
|
x-forwarded-proto: https\r
|
|
226
|
-
x-forwarded-host: ${
|
|
227
|
-
`;if(
|
|
228
|
-
`;let
|
|
229
|
-
`}if(
|
|
230
|
-
`,
|
|
231
|
-
`;return
|
|
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,Fj,u$,M2=1048576,Kj=30000,YH=16384,I2=262144,AH=2097152,XH=524288,JH=8192,UH=4096,WH,y2,jH,H8;var S2=s(()=>{({connect:rq}=Bun),VY=Symbol("rpx.pool.fallback"),q8=Symbol("rpx.pool.stale"),tq=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Fj=Symbol("rpx.pool.timeout"),u$=Symbol("rpx.pool.busy");WH=new TextEncoder,y2=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 _2(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 h2(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 IH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function LH(w){if(!w)return!1;let $=null;for(let Y of w.split(",")){let[A,...X]=Y.trim().split(";"),J=A.trim().toLowerCase();if(J!=="gzip"&&J!=="*")continue;let U=1;for(let j of X){let W=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(j);if(W)U=Number.parseFloat(W[1])}if(J==="gzip")return Number.isFinite(U)&&U>0;$=U}return $!==null&&Number.isFinite($)&&$>0}function OH(w){let $=w.get("vary");if(!$){w.set("vary","Accept-Encoding");return}if(!$.split(",").some((Y)=>Y.trim().toLowerCase()==="accept-encoding"))w.set("vary",`${$}, Accept-Encoding`)}function SH(w,$){if(w.method==="HEAD"||$.status===204||$.status===206||$.status===304||!$.body||$.headers.has("content-encoding")||$.headers.get("cache-control")?.toLowerCase().includes("no-transform")||w.headers.has("range")||!LH(w.headers.get("accept-encoding")))return $;let Y=$.headers.get("content-type")?.toLowerCase()??"";if(!CH.some((J)=>Y.startsWith(J)))return $;let A=$.headers.get("content-length");if(A!==null){let J=Number.parseInt(A,10);if(Number.isFinite(J)&&J<VH)return $}let X=new Headers($.headers);return X.set("content-encoding","gzip"),OH(X),X.delete("content-length"),X.delete("content-md5"),X.delete("content-digest"),X.delete("accept-ranges"),X.delete("etag"),new Response($.body.pipeThrough(new CompressionStream("gzip")),{status:$.status,statusText:$.statusText,headers:X})}function _H(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,K("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function hH(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}=hH(X.url),W=_H(X),Q=w(W,U);if(!Q&&Y){let E=await Y(W,U,X);if(E instanceof Response)return E;if(E&&E.retry)Q=w(W,U)}if(!Q)return K("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(Q.auth){let E=H2(X,U,Q.auth);if(E)return K("request",`401 challenge for ${W}${U}`,$),E}if(Q.redirect){let E=h2(Q.redirect,U,j);return K("request",`${Q.redirect.status} redirect ${W}${U} → ${E}`,$),new Response(null,{status:Q.redirect.status,headers:{location:E}})}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 E=x2(Q);if(!J||!E)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:N,targetPath:R}=k2(U,Q,E,$),V=`ws://${N}${R}${j}`,L={};for(let[M,D]of X.headers)if(!yH.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})){K("ws",`upgraded ${W}${R} → ${V}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let z=x2(Q);if(!z)return new Response(`No upstream configured for ${W}`,{status:502});if(Q.cleanUrls&&U.endsWith(".html")){let E=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:E}})}let{targetHost:f,targetPath:B}=k2(U,Q,z,$),G=Q.changeOrigin?`http://${f}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",F=Q.upstreamPool;if(F)z.activeConnections++;try{let E=await L2({hostPort:f,method:X.method,path:`${B}${j}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body,signal:X.signal});if(F)T8(F,z);return E}catch(E){if(E===Fj){if(K("request",`Upstream timeout for ${W}`,$),F)MY(F,z);return new Response("Gateway Timeout",{status:504})}if(E===u$)return K("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(E===VY||!T)try{let N=new Headers(X.headers);if(N.set("host",f),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://${f}${B}${j}`,{method:X.method,headers:N,body:X.body,redirect:"manual"});if(F)T8(F,z);return R}catch(N){if(K("request",`Proxy error for ${W}: ${N}`,$),F)MY(F,z);return new Response(`Proxy Error: ${N}`,{status:502})}if(K("request",`Proxy error for ${W}: ${E}`,$),F)MY(F,z);return new Response(`Proxy Error: ${E}`,{status:502})}finally{if(F)z.activeConnections--}};return async(X,J)=>{try{let U=await A(X,J);return U?SH(X,U):U}catch(U){return K("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function OY(w){let $=new WeakMap,Y=IH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){K("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",()=>{K("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){K("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 yH,CH,VH=1024;var Ej=s(()=>{N8();S2();M8();f0();yH=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),CH=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"]});import*as i2 from"node:fs";import*as b2 from"node:path";function I8(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 DH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function SY(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(!W1(J))continue;if(h$($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}function _Y(w,$,Y){let A=Nj(w,$);if(!A)return;for(let X of A)if(DH(Y,X.path))return X.route;return}var y8=()=>{};import*as hY from"node:fs/promises";import*as qj from"node:path";function v$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}function xH(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 kH(w,$,Y,A){try{let[X,J]=await Promise.all([hY.readFile($,"utf8"),hY.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return K("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 hY.readdir(w.certsDir)}catch(U){K("sni",`certsDir read failed (${w.certsDir}): ${U.message}`,$)}for(let U of J){let j=xH(U);if(!j)continue;if(A&&!A.has(j))continue;let W=U.slice(0,-4);Y.set(j,{certPath:qj.join(w.certsDir,U),keyPath:qj.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 kH(J,U.certPath,U.keyPath,$);if(j)X.push(j)}return X}var Hj=s(()=>{f0()});import*as Vw 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 iH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function v2(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 b1{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??PH;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(!v2(w))return!1;if(iH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return K("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(!v2(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 K("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 K("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{K("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),K("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),K("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([Vw.readFile($,"utf8"),Vw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),K("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 Vw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([Vw.writeFile(A,$,"utf8"),Vw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return C8.join(this.certsDir,ZH)}async loadAccountKey(){try{return await Vw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await Vw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Vw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var ZH="acme-account.key",PH=60000,u2=4096;var Rj=s(()=>{xX();f0()});import*as V8 from"node:net";function I$(w,$,Y){return K("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=V8.createServer(),J=setTimeout(()=>{K("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")K("port",`Port ${w} is in use`,Y),A(!0);else K("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),K("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),K("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function Mj(w,$,Y,A=50){K("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await I$(X,$,Y))return K("port",`Found available port: ${X} after ${J} attempts`,Y),X;K("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 c2(w,$,Y=5000,A){return K("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=V8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{K("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{K("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{K("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 I$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await c2(w,this.hostname,3000,this.verbose))return K("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 c2(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){K("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var bL;var Ij=s(()=>{f0();bL=new L8});import*as O8 from"node:fs";import*as t0 from"node:fs/promises";import{homedir as bH}from"node:os";import*as yj from"node:path";import*as S8 from"node:process";function Xw(){return yj.join(bH(),".stacks","rpx","registry.d")}function y$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&uH.test(w)}function Cj(w,$){if(!y$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return yj.join(w,`${$}.json`)}function Jw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return S8.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"&&y$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function vH(w){await t0.mkdir(w,{recursive:!0})}async function u1(w,$=Xw(),Y){if(!m2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await vH($);let A=Cj($,w.id),X=`${A}.tmp.${S8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await t0.writeFile(X,J,{encoding:"utf8",mode:420}),await t0.rename(X,A),K("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await t0.unlink(X).catch(()=>{}),U}}async function c$(w,$=Xw(),Y){let A=Cj($,w);try{await t0.unlink(A),K("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function Vj(w,$=Xw(),Y){let A=Cj($,w);try{let X=await t0.readFile(A,"utf8"),J=JSON.parse(X);if(!m2(J))return K("registry",`entry ${w} failed validation, removing`,Y),await t0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return K("registry",`entry ${w} has invalid JSON, removing`,Y),await t0.unlink(A).catch(()=>{}),null;throw X}}async function Tw(w=Xw(),$){let Y;try{Y=await t0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!y$(J))continue;let U=await Vj(J,w,$);if(U)A.push(U)}return A}async function kY(w=Xw(),$){let Y=await Tw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Jw(X.pid))K("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await c$(X.id,w,$).catch(()=>{}),A++}return A}function _8(w,$={}){let Y=$.dir??Xw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;O8.mkdirSync(Y,{recursive:!0});let U=null,j=!1,W=null,Q=!1,z=(E)=>{return JSON.stringify(E.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)))},f=()=>{if(U=null,j)return;Tw(Y,J).then((E)=>{return W=z(E),w(E)}).catch((E)=>{K("registry",`watcher onChange failed: ${E}`,J)})},B=()=>{if(j)return;if(U)clearTimeout(U);U=setTimeout(f,A)},T=setInterval(()=>{if(j||Q)return;Q=!0,Tw(Y,J).then((E)=>{if(z(E)!==W)B()}).catch((E)=>{K("registry",`watcher poll failed: ${E}`,J)}).finally(()=>{Q=!1})},X),F=O8.watch(Y,{persistent:!0},(E,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;B()});return F.on("error",(E)=>{K("registry",`watcher error: ${E}`,J)}),B(),{close:()=>{if(j=!0,U)clearTimeout(U);clearInterval(T),F.close()}}}var uH;var m$=s(()=>{f0();uH=/^[a-zA-Z0-9._-]+$/});import{closeSync as g2,openSync as cH,readFileSync as mH}from"node:fs";import*as d2 from"node:fs/promises";import{spawn as gH}from"node:child_process";import{homedir as dH}from"node:os";import*as ZY from"node:path";import*as Lw from"node:process";class Oj{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??Xw(),this.rpxDir=w.rpxDir??ZY.join(dH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??nH,this.pollIntervalMs=w.pollIntervalMs??lH,this.restartDelayMs=w.restartDelayMs??rH,this.killGraceMs=w.killGraceMs??tH,this.launch=w.launcher??sH(this.verbose),this.probePort=w.probePort??aH,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??u1,this.removeEntry=w.removeEntry??c$;let $=w.reapIntervalMs??pH;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)=>{K("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(Lw.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 mH(w.logPath,"utf8").split(`
|
|
233
|
-
`).slice(
|
|
234
|
-
`).trim()}catch{return""}}async stop(
|
|
227
|
+
x-forwarded-host: ${n}\r
|
|
228
|
+
`;if(o!==void 0)l+=`origin: ${o}\r
|
|
229
|
+
`;let u=!1;for(let[f,h]of r){let d=f.toLowerCase();if(zT.has(d))continue;if(o!==void 0&&d==="origin")continue;if(d==="content-length")u=!0;l+=`${f}: ${h}\r
|
|
230
|
+
`}if(l+=`connection: keep-alive\r
|
|
231
|
+
`,c&&!u)l+=`content-length: ${c.length}\r
|
|
232
|
+
`;return l+=`\r
|
|
233
|
+
`,YT.encode(l)}async function iP(e){let t=e.getReader(),r=[],i=0;for(;;){let{done:o,value:c}=await t.read();if(o)break;if(c){if(i+=c.length,i>yy)return t.cancel().catch(()=>{}),null;r.push(c)}}if(r.length===1)return r[0];let n=new Uint8Array(i),s=0;for(let o of r)n.set(o,s),s+=o.length;return n}var DT,Pn,wa,FT,df,_r,yy=1048576,hf=30000,UT=16384,wy=262144,WT=2097152,KT=524288,HT=8192,VT=4096,YT,vy,zT,va;var Sy=Q(()=>{({connect:DT}=Bun),Pn=Symbol("rpx.pool.fallback"),wa=Symbol("rpx.pool.stale"),FT=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);df=Symbol("rpx.pool.timeout"),_r=Symbol("rpx.pool.busy");YT=new TextEncoder,vy=new TextDecoder,zT=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"]);va=new Map});function Ey(e){let t=typeof e==="string"?{to:e}:e,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function Ty(e,t,r){if(!e.preservePath)return e.to||"/";let i=`${t}${r}`;return i==="/"?`${e.to}/`:`${e.to}${i}`}import*as yt from"node:path";function ba(e,t){if(typeof e==="string")return{dir:e,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:e.dir,spa:e.spa??!1,pathRewriteStyle:e.pathRewriteStyle??"directory",maxAge:e.maxAge??0,cleanUrls:t}}function sP(e){let t=yt.extname(e).toLowerCase();return nP[t]??"application/octet-stream"}function oP(e){let t;try{t=decodeURIComponent(e)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=yt.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function aP(e,t){let r=oP(e);if(r===null)return null;let i=yt.posix.extname(r);if(t.cleanUrls&&i===".html"){let n=e.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:yt.join(t.dir,r),redirectTo:n||"/"}}if(r===""||e.endsWith("/"))return{filePath:yt.join(t.dir,r,"index.html")};if(i!=="")return{filePath:yt.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:yt.join(t.dir,`${r}.html`)};return{filePath:yt.join(t.dir,r,"index.html")}}async function Py(e,t){let r=aP(e,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let i=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",n=Bun.file(r.filePath);if(await n.exists())return new Response(n,{status:200,headers:{"Content-Type":sP(r.filePath),"Cache-Control":i}});if(t.spa){let s=yt.join(t.dir,"index.html"),o=Bun.file(s);if(await o.exists())return new Response(o,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var nP;var $a=Q(()=>{nP={".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 cP(e,t){let r;try{r=t?.requestIP?.(e)?.address}catch{return mf}if(!r)return mf;return/^[0-9a-f.:]{1,45}$/i.test(r)?r:mf}function lP(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function dP(e){if(!e)return!1;let t=null;for(let r of e.split(",")){let[i,...n]=r.trim().split(";"),s=i.trim().toLowerCase();if(s!=="gzip"&&s!=="*")continue;let o=1;for(let c of n){let a=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(c);if(a)o=Number.parseFloat(a[1])}if(s==="gzip")return Number.isFinite(o)&&o>0;t=o}return t!==null&&Number.isFinite(t)&&t>0}function mP(e){let t=e.get("vary");if(!t){e.set("vary","Accept-Encoding");return}if(!t.split(",").some((r)=>r.trim().toLowerCase()==="accept-encoding"))e.set("vary",`${t}, Accept-Encoding`)}function gP(e,t){if(e.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||e.headers.has("range")||!dP(e.headers.get("accept-encoding")))return t;let r=t.headers.get("content-type")?.toLowerCase()??"";if(!fP.some((s)=>r.startsWith(s)))return t;let i=t.headers.get("content-length");if(i!==null){let s=Number.parseInt(i,10);if(Number.isFinite(s)&&s<hP)return t}let n=new Headers(t.headers);return n.set("content-encoding","gzip"),mP(n),n.delete("content-length"),n.delete("content-md5"),n.delete("content-digest"),n.delete("accept-ranges"),n.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:n})}function pP(e){let t=e.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function ky(e,t){if(!t||t==="/")return e;if(e===t)return"/";if(e.startsWith(`${t}/`)){let r=e.slice(t.length);return r===""?"/":r}return e}function Ry(e){if(e.upstreamPool)return hy(e.upstreamPool);if(e.sourceHost)return{url:e.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function Ay(e,t,r,i){let n=r?.url??t.sourceHost??"",o=t.stripBasePathPrefix??!1?ky(e,t.basePath):e,c=Zu(o,t.pathRewrites);if(c)n=c.targetHost,o=c.targetPath,m("request",`Path rewrite: ${e} → ${n}${o}`,i);return{targetHost:n,targetPath:o}}function yP(e){let t=e.indexOf("://"),r=t===-1?e.indexOf("/"):e.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let i=e.indexOf("?",r);if(i===-1)return{pathname:e.slice(r),search:""};return{pathname:e.slice(r,i),search:e.slice(i)}}function Rn(e,t,r){let i=async(n,s)=>{let{pathname:o,search:c}=yP(n.url),a=pP(n),l=cP(n,s),u=e(a,o);if(!u&&r){let w=await r(a,o,n);if(w instanceof Response)return w;if(w&&w.retry)u=e(a,o)}if(!u)return m("request",`No route found for host: ${a}`,t),new Response(`No proxy configured for ${a}`,{status:404});if(u.auth){let w=gy(n,o,u.auth);if(w)return m("request",`401 challenge for ${a}${o}`,t),w}if(u.redirect){let w=Ty(u.redirect,o,c);return m("request",`${u.redirect.status} redirect ${a}${o} → ${w}`,t),new Response(null,{status:u.redirect.status,headers:{location:w}})}if(u.static){let b=u.stripBasePathPrefix??!0?ky(o,u.basePath):o;return Py(b,u.static)}if(n.headers.get("upgrade")?.toLowerCase()==="websocket"){let w=Ry(u);if(!s||!w)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:b,targetPath:P}=Ay(o,u,w,t),R=`ws://${b}${P}${c}`,v={};for(let[D,W]of n.headers)if(!uP.has(D.toLowerCase())&&D.toLowerCase()!=="host")v[D]=W;v.host=b,v["x-forwarded-for"]=l,v["x-real-ip"]=l,v["x-forwarded-proto"]="https",v["x-forwarded-host"]=a;let T={targetUrl:R,forwardHeaders:v};if(s.upgrade(n,{data:T})){m("ws",`upgraded ${a}${P} → ${R}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let f=Ry(u);if(!f)return new Response(`No upstream configured for ${a}`,{status:502});if(u.cleanUrls&&o.endsWith(".html")){let w=o.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:w}})}let{targetHost:h,targetPath:d}=Ay(o,u,f,t),y=u.changeOrigin?`http://${h}`:void 0,g=n.body!=null&&n.method!=="GET"&&n.method!=="HEAD",p=u.upstreamPool;if(p)f.activeConnections++;try{let w=await xy({hostPort:h,method:n.method,path:`${d}${c}`,reqHeaders:n.headers,forwardedHost:a,clientIp:l,originOverride:y,body:n.body,signal:n.signal});if(p)pa(p,f);return w}catch(w){if(w===df){if(m("request",`Upstream timeout for ${a}`,t),p)Cn(p,f);return new Response("Gateway Timeout",{status:504})}if(w===_r)return m("request",`Upstream pool saturated for ${a}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(w===Pn||!g)try{let b=new Headers(n.headers);if(b.set("host",h),b.set("x-forwarded-for",l),b.set("x-real-ip",l),b.set("x-forwarded-proto","https"),b.set("x-forwarded-host",a),y!==void 0)b.set("origin",y);let P=await fetch(`http://${h}${d}${c}`,{method:n.method,headers:b,body:n.body,redirect:"manual"});if(p)pa(p,f);return P}catch(b){if(m("request",`Proxy error for ${a}: ${b}`,t),p)Cn(p,f);return new Response(`Proxy Error: ${b}`,{status:502})}if(m("request",`Proxy error for ${a}: ${w}`,t),p)Cn(p,f);return new Response(`Proxy Error: ${w}`,{status:502})}finally{if(p)f.activeConnections--}};return async(n,s)=>{try{let o=await i(n,s);return o?gP(n,o):o}catch(o){return m("request",`Unhandled proxy handler error: ${o}`,t),new Response("Bad Gateway",{status:502})}}}function An(e){let t=new WeakMap,r=lP();return{open(i){let{targetUrl:n,forwardHeaders:s}=i.data,o;try{o=new WebSocket(n,{headers:s})}catch(a){m("ws",`failed to open upstream ${n}: ${a}`,e),i.close(1011,"upstream connect failed");return}o.binaryType="arraybuffer";let c={upstream:o,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(i,c),o.addEventListener("open",()=>{c.upstreamOpen=!0;for(let a of c.pending)o.send(a);c.pending=[],c.pendingBytes=0}),o.addEventListener("message",(a)=>{i.send(a.data)}),o.addEventListener("close",(a)=>{try{i.close(a.code||1000,a.reason||"")}catch{}}),o.addEventListener("error",()=>{m("ws",`upstream error for ${n}`,e);try{i.close(1011,"upstream error")}catch{}})},message(i,n){let s=t.get(i);if(!s)return;let o=typeof n==="string"?n:new Uint8Array(n);if(s.upstreamOpen){s.upstream.send(o);return}let c=typeof o==="string"?Buffer.byteLength(o):o.byteLength;if(s.pendingBytes+c>r){m("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,e);try{i.close(1009,"buffer limit")}catch{}try{s.upstream.close(1011,"client buffer overflow")}catch{}t.delete(i);return}s.pending.push(o),s.pendingBytes+=c},close(i,n,s){let o=t.get(i);if(!o)return;t.delete(i);try{o.upstream.close(n||1000,s||"")}catch{}}}}var mf="127.0.0.1",uP,fP,hP=1024;var gf=Q(()=>{ya();Sy();$a();he();uP=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),fP=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"]});import*as Ny from"node:fs";import*as Dy from"node:path";function xa(e,t){if(!e||!t.startsWith(Oy))return null;let r=t.slice(Oy.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return Ny.readFileSync(Dy.join(e,r),"utf8")}catch{return null}}var Oy="/.well-known/acme-challenge/";var pf=()=>{};function rr(e){if(!e||e==="/")return"/";let t=e.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function wP(e,t){if(t==="/")return!0;if(e===t)return!0;return e.startsWith(`${t}/`)}function kn(e){let t=new Map;for(let i of e){let n=rr(i.path),s=t.get(i.host);if(!s)s=new Map,t.set(i.host,s);s.set(n,i.route)}let r=new Map;for(let[i,n]of t){let s=[];for(let[o,c]of n)s.push({path:o,route:c});s.sort((o,c)=>c.path.length-o.path.length),r.set(i,s)}return r}function yf(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!ai(s))continue;if(Or(t,s)){let c=s.length-1;if(c>n)n=c,i=o}}return i}function On(e,t,r){let i=yf(e,t);if(!i)return;for(let n of i)if(wP(r,n.path))return n.route;return}var Ca=()=>{};import*as Nn from"node:fs/promises";import*as wf from"node:path";function jr(e){if(Array.isArray(e))return e.map((t)=>({...t,lowMemoryMode:!0}));return{...e,lowMemoryMode:!0}}function vP(e){if(!e.endsWith(".crt"))return null;let t=e.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function bP(e,t,r,i){try{let[n,s]=await Promise.all([Nn.readFile(t,"utf8"),Nn.readFile(r,"utf8")]);return{serverName:e,cert:n,key:s}}catch(n){return m("sni",`skipping ${e}: ${n.message}`,i),null}}async function Dn(e,t){let r=new Map,i=e.certsDirServerNames?new Set(e.certsDirServerNames):void 0;if(e.certsDir){let s=[];try{s=await Nn.readdir(e.certsDir)}catch(o){m("sni",`certsDir read failed (${e.certsDir}): ${o.message}`,t)}for(let o of s){let c=vP(o);if(!c)continue;if(i&&!i.has(c))continue;let a=o.slice(0,-4);r.set(c,{certPath:wf.join(e.certsDir,o),keyPath:wf.join(e.certsDir,`${a}.key`)})}}if(e.domains)for(let[s,o]of Object.entries(e.domains))r.set(s,o);let n=[];for(let[s,o]of r){let c=await bP(s,o.certPath,o.keyPath,t);if(c)n.push(c)}return n}var vf=Q(()=>{he()});import*as Pt from"node:fs/promises";import*as Sa from"node:path";function Fn(e=process.env){let t=e.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return e.INVOCATION_ID?"restart":"rebind"}function CP(e,t){if(!t||t.length===0)return!1;return t.some((r)=>{let i=r.startsWith(".")?r.slice(1):r;return e===i||e.endsWith(`.${i}`)})}function By(e){if(!e||e.length>253)return!1;if(e.includes("/")||e.includes(":")||e.includes(" "))return!1;if(e.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)}class Ii{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(e){this.config=e.config,this.certsDir=e.certsDir,this.onCertAdded=e.onCertAdded,this.http01Store=e.http01Store??So,this.issuer=e.issuer??ql,this.verbose=e.verbose??!1,this.negativeCacheMs=e.negativeCacheMs??xP;for(let t of e.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(e){return this.certs.has(e)}async isApproved(e){if(!By(e))return!1;if(CP(e,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(e)}catch(t){return m("on-demand",`ask(${e}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(e){if(!this.config.enabled)return!1;if(this.certs.has(e))return!0;if(!By(e))return!1;let t=this.inFlight.get(e);if(t)return t;let r=this.negativeCache.get(e);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(e))return this.negativeCache.delete(e),!0;return m("on-demand",`${e} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let i=this.issue(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,i),i}async issue(e){if(this.certs.has(e))return!0;if(await this.loadFromDisk(e))return!0;if(!await this.isApproved(e))return m("on-demand",`refused issuance for ${e} (not approved)`,this.verbose),this.cacheNegative(e),!1;try{m("on-demand",`issuing cert for ${e} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[e],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(e,t.fullChainPem,t.keyPem);let r={serverName:e,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(e,r),this.negativeCache.delete(e),m("on-demand",`issued + installed cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(e),m("on-demand",`issuance for ${e} failed: ${t.message}`,this.verbose),!1}}cacheNegative(e){if(this.negativeCache.size>=Fy){let t=Date.now();for(let[r,i]of this.negativeCache)if(i<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=Fy){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(e,Date.now()+this.negativeCacheMs)}async loadFromDisk(e){let{certPath:t,keyPath:r}=this.pathsFor(e);try{let[i,n]=await Promise.all([Pt.readFile(t,"utf8"),Pt.readFile(r,"utf8")]),s={serverName:e,cert:i,key:n};return this.certs.set(e,s),m("on-demand",`adopted existing on-disk cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(e){return{certPath:Sa.join(this.certsDir,`${e}.crt`),keyPath:Sa.join(this.certsDir,`${e}.key`)}}async persist(e,t,r){await Pt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:i,keyPath:n}=this.pathsFor(e);await Promise.all([Pt.writeFile(i,t,"utf8"),Pt.writeFile(n,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Sa.join(this.certsDir,$P)}async loadAccountKey(){try{return await Pt.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(e){if(!e||this.accountKeyPem===e)return;this.accountKeyPem=e,await Pt.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Pt.writeFile(this.accountKeyPath,e,{encoding:"utf8",mode:384}).catch(()=>{})}}var $P="acme-account.key",xP=60000,Fy=4096;var bf=Q(()=>{No();he()});import*as Ea from"node:net";function Cr(e,t,r){return m("port",`Checking if port ${e} is in use on ${t}`,r),new Promise((i)=>{let n=Ea.createServer(),s=setTimeout(()=>{m("port",`Checking port ${e} timed out, assuming it's in use`,r),n.close(),i(!0)},3000);n.once("error",(o)=>{if(clearTimeout(s),o.code==="EADDRINUSE")m("port",`Port ${e} is in use`,r),i(!0);else m("port",`Error checking port ${e}: ${o.message}`,r),i(!0)}),n.once("listening",()=>{clearTimeout(s),m("port",`Port ${e} is available`,r),n.close(),i(!1)});try{n.listen(e,t)}catch(o){clearTimeout(s),m("port",`Exception checking port ${e}: ${o}`,r),i(!0)}})}async function $f(e,t,r,i=50){m("port",`Finding available port starting from ${e} (max attempts: ${i})`,r);let n=e,s=0;while(s<i){if(s++,!await Cr(n,t,r))return m("port",`Found available port: ${n} after ${s} attempts`,r),n;m("port",`Port ${n} is in use, trying ${n+1} (attempt ${s}/${i})`,r),n++}throw Error(`Unable to find available port after ${i} attempts starting from ${e}`)}function Ly(e,t,r=5000,i){return m("port",`Testing connection to ${t}:${e}`,i),new Promise((n)=>{let s=Ea.connect({host:t,port:e,timeout:r});s.once("connect",()=>{m("port",`Successfully connected to ${t}:${e}`,i),s.end(),n(!0)}),s.once("timeout",()=>{m("port",`Connection to ${t}:${e} timed out`,i),s.destroy(),n(!1)}),s.once("error",(o)=>{m("port",`Failed to connect to ${t}:${e}: ${o.message}`,i),s.destroy(),n(!1)})})}class Ta{usedPorts=new Set;hostname;verbose;maxRetries;constructor(e="0.0.0.0",t,r=50){this.hostname=e,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(e,t=!1){if(this.usedPorts.has(e))return this.findNextAvailablePort(e+1,t);if(await Cr(e,this.hostname,this.verbose))return this.findNextAvailablePort(e+1,t);if(t){if(!await Ly(e,this.hostname,3000,this.verbose))return m("port",`Port ${e} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(e+1,t)}return this.usedPorts.add(e),e}async findNextAvailablePort(e,t=!1){let r=await $f(e,this.hostname,this.verbose,this.maxRetries);if(t){if(!await Ly(r,this.hostname,3000,this.verbose))if(r<e+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(e){m("port",`Releasing port ${e}`,this.verbose),this.usedPorts.delete(e)}}var EB;var xf=Q(()=>{he();EB=new Ta});import*as Pa from"node:fs";import*as Je from"node:fs/promises";import{homedir as SP}from"node:os";import*as Cf from"node:path";import*as Ra from"node:process";function st(){return Cf.join(SP(),".stacks","rpx","registry.d")}function Sr(e){return typeof e==="string"&&e.length>0&&e.length<=128&&EP.test(e)}function Sf(e,t){if(!Sr(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Cf.join(e,`${t}.json`)}function ot(e){if(!Number.isInteger(e)||e<=0)return!1;try{return Ra.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function My(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,i=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,n=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",s=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&Sr(t.id)&&(i||n)&&typeof t.to==="string"&&t.to.length>0&&s&&r&&typeof t.createdAt==="string"}async function TP(e){await Je.mkdir(e,{recursive:!0})}async function _i(e,t=st(),r){if(!My(e))throw Error(`invalid registry entry: ${JSON.stringify(e)}`);await TP(t);let i=Sf(t,e.id),n=`${i}.tmp.${Ra.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{await Je.writeFile(n,s,{encoding:"utf8",mode:420}),await Je.rename(n,i),m("registry",`wrote entry ${e.id} → ${i}`,r)}catch(o){throw await Je.unlink(n).catch(()=>{}),o}}async function Ur(e,t=st(),r){let i=Sf(t,e);try{await Je.unlink(i),m("registry",`removed entry ${e}`,r)}catch(n){if(n.code!=="ENOENT")throw n}}async function Ef(e,t=st(),r){let i=Sf(t,e);try{let n=await Je.readFile(i,"utf8"),s=JSON.parse(n);if(!My(s))return m("registry",`entry ${e} failed validation, removing`,r),await Je.unlink(i).catch(()=>{}),null;return s}catch(n){if(n.code==="ENOENT")return null;if(n instanceof SyntaxError)return m("registry",`entry ${e} has invalid JSON, removing`,r),await Je.unlink(i).catch(()=>{}),null;throw n}}async function wt(e=st(),t){let r;try{r=await Je.readdir(e)}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.endsWith(".json"))continue;let s=n.slice(0,-5);if(!Sr(s))continue;let o=await Ef(s,e,t);if(o)i.push(o)}return i}async function Bn(e=st(),t){let r=await wt(e,t),i=0;for(let n of r){if(n.pid===void 0)continue;if(!ot(n.pid))m("registry",`GC: pid ${n.pid} for ${n.id} is dead, removing`,t),await Ur(n.id,e,t).catch(()=>{}),i++}return i}function Aa(e,t={}){let r=t.dir??st(),i=t.debounceMs??100,n=t.pollMs??Math.max(i*2,250),s=t.verbose;Pa.mkdirSync(r,{recursive:!0});let o=null,c=!1,a=null,l=!1,u=(p)=>JSON.stringify(p.map((w)=>({id:w.id,from:w.from,to:w.to,path:w.path,pid:w.pid,pathRewrites:w.pathRewrites,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,static:w.static,loadBalancer:w.loadBalancer})).sort((w,b)=>w.id.localeCompare(b.id))),f=()=>{if(o=null,c)return;wt(r,s).then((p)=>(a=u(p),e(p))).catch((p)=>{m("registry",`watcher onChange failed: ${p}`,s)})},h=()=>{if(c)return;if(o)clearTimeout(o);o=setTimeout(f,i)},y=setInterval(()=>{if(c||l)return;l=!0,wt(r,s).then((p)=>{if(u(p)!==a)h()}).catch((p)=>{m("registry",`watcher poll failed: ${p}`,s)}).finally(()=>{l=!1})},n),g=Pa.watch(r,{persistent:!0},(p,w)=>{if(w&&/\.tmp\.\d+\.\d+$/.test(w))return;h()});return g.on("error",(p)=>{m("registry",`watcher error: ${p}`,s)}),h(),{close:()=>{if(c=!0,o)clearTimeout(o);clearInterval(y),g.close()}}}var EP;var Wr=Q(()=>{he();EP=/^[a-zA-Z0-9._-]+$/});import{closeSync as Iy,openSync as PP,readFileSync as RP}from"node:fs";import*as _y from"node:fs/promises";import{spawn as AP}from"node:child_process";import{homedir as kP}from"node:os";import*as Ln from"node:path";import*as Rt from"node:process";class Pf{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(e){this.resolver=e.resolver,this.registryDir=e.registryDir??st(),this.rpxDir=e.rpxDir??Ln.join(kP(),".stacks","rpx"),this.verbose=e.verbose??!1,this.startupTimeoutMs=e.startupTimeoutMs??OP,this.pollIntervalMs=e.pollIntervalMs??NP,this.restartDelayMs=e.restartDelayMs??FP,this.killGraceMs=e.killGraceMs??BP,this.launch=e.launcher??MP(this.verbose),this.probePort=e.probePort??LP,this.pickPort=e.pickPort??((r)=>$f(r,"127.0.0.1")),this.isHostRoutable=e.isHostRoutable??(()=>!1),this.onSiteActivating=e.onSiteActivating,this.now=e.now??Date.now,this.writeEntry=e.writeEntry??_i,this.removeEntry=e.removeEntry??Ur;let t=e.reapIntervalMs??DP;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(e){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(e);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(e),t=void 0;if(!t){let r=this.resolver.resolve(e);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:e};if(t.status==="failed")return{kind:"failed",host:e,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:e,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(e){try{this.onSiteActivating?.(e.host)}catch{}let t=new Map;if(!e.selfRegisters)for(let c of e.routes){if(t.has(c.portEnv))continue;let a=await this.pickPort(c.defaultPort??3000);t.set(c.portEnv,a)}let r=Ln.join(this.rpxDir,"sites",`${e.id}.log`);await _y.mkdir(Ln.dirname(r),{recursive:!0}).catch(()=>{});let i=this.buildEnv(e,t),n=null,s;try{n=this.launch({command:e.command,cwd:e.dir,env:i,logPath:r})}catch(c){s=`failed to spawn: ${c.message}`}let o={site:e,status:s?"failed":"starting",handle:n,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:s?this.now():0,error:s,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(e.host,o),s)return x.warn(`rpx: site ${e.host} ${s}`),o;return x.info(`rpx: booting ${e.host} → ${e.command} (${e.dir})`),n.exited.then((c)=>this.onProcessExit(o,c)).catch(()=>{}),o.ready=this.driveReadiness(o).catch((c)=>{m("sites",`readiness loop for ${e.host} threw: ${c}`,this.verbose)}),o}async onProcessExit(e,t){if(e.exited=!0,this.stopped||this.sites.get(e.site.host)!==e)return;if(e.status==="ready"){x.warn(`rpx: ${e.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(e.site.host);for(let r of e.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(e.status==="starting")this.fail(e,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(e){let{site:t}=e,r=this.now()+this.startupTimeoutMs,i=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,e.ports);while(this.now()<r&&!this.stopped){if(e.status!=="starting"||e.exited)return;if(await i()){if(await this.publishRoutes(e),e.status==="starting")e.status="ready",x.success(`rpx: ${t.host} ready`);return}await Tf(this.pollIntervalMs)}if(e.status==="starting")this.fail(e,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(e,t){let r=e.routes.filter((n)=>n.readyGate??rr(n.path)==="/").map((n)=>t.get(n.portEnv)).filter((n)=>typeof n==="number"),i=r.length>0?r:[...t.values()];return async()=>{for(let n of i)if(!await this.probePort(n))return!1;return i.length>0}}async publishRoutes(e){let{site:t,ports:r}=e;if(t.selfRegisters||t.routes.length===0)return;let i=t.routes.find((a)=>rr(a.path)==="/")??t.routes[0],n=r.get(i.portEnv);if(n===void 0)return;let s=[];for(let a of t.routes){if(a===i)continue;let l=r.get(a.portEnv);if(l===void 0)continue;s.push({from:rr(a.path),to:`localhost:${l}`,stripPrefix:a.stripPrefix??!1})}let o={id:t.id,from:`localhost:${n}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:s.length>0?s:void 0,pid:e.handle?.pid};await this.writeEntry(o,this.registryDir,this.verbose),e.routeIds=[t.id];let c=this.now()+2000;while(this.now()<c&&!this.isHostRoutable(t.host))await Tf(50)}fail(e,t){e.status="failed",e.error=t,e.failedAt=this.now(),x.warn(`rpx: site ${e.site.host} failed — ${t}`),this.killProcess(e)}buildEnv(e,t){let r={};for(let[i,n]of Object.entries(Rt.env))if(typeof n==="string")r[i]=n;Object.assign(r,e.env);for(let[i,n]of t)r[i]=String(n);return r.RPX_SITE_HOST=e.host,r.RPX_SITE_URL=`https://${e.host}`,r}readLogTail(e,t=40){try{return RP(e.logPath,"utf8").split(`
|
|
234
|
+
`).slice(-t).join(`
|
|
235
|
+
`).trim()}catch{return""}}async stop(e){let t=this.sites.get(e);if(!t)return;this.sites.delete(e);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),x.info(`rpx: stopped ${e}`)}async killProcess(e){let t=e.handle;if(!t)return;e.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),Tf(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let e=this.now();for(let[t,r]of this.sites){let i=r.site.idleTimeoutMs;if(i<=0)continue;let n=e-r.lastAccess;if((r.status==="ready"||e-r.startedAt>this.startupTimeoutMs)&&n>i)m("sites",`reaping ${t} (idle ${Math.round(n/1000)}s)`,this.verbose),await this.stop(t)}}list(){let e=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:e-t.startedAt,idleMs:e-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((e)=>this.stop(e)))}}function Tf(e){return new Promise((t)=>setTimeout(t,e))}async function LP(e){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${e}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function MP(e){let t=IP();return({command:r,cwd:i,env:n,logPath:s})=>{let o=PP(s,"a");try{let c=AP("sh",["-c",r],{cwd:i,env:n,detached:!0,stdio:["ignore",o,o],...t?{uid:t.uid,gid:t.gid}:{}}),a=c.pid;if(a===void 0)throw Error("spawn returned no pid");let l=new Promise((u)=>{c.once("exit",(f)=>{u(f)}),c.once("error",()=>{u(null)})}).finally(()=>{try{Iy(o)}catch{}});return m("sites",`spawned pid ${a}: sh -c ${r} (cwd ${i})`,e),{pid:a,exited:l,stop:(u="SIGTERM")=>{try{Rt.kill(-a,u)}catch{try{c.kill(u)}catch{}}}}}catch(c){try{Iy(o)}catch{}throw c}}}function IP(){if(Rt.platform==="win32")return null;if(!(typeof Rt.getuid==="function"&&Rt.getuid()===0))return null;let t=Number.parseInt(Rt.env.SUDO_UID??"",10),r=Number.parseInt(Rt.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}var OP=120000,NP=200,DP=30000,FP=3000,BP=4000;var jy=Q(()=>{Ca();xf();Wr();he();Nr()});function ji(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Uy(e,t,r){return`<!doctype html>
|
|
235
236
|
<html lang="en">
|
|
236
237
|
<head>
|
|
237
238
|
<meta charset="utf-8">
|
|
238
239
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
239
|
-
${
|
|
240
|
-
<title>${
|
|
241
|
-
<style>${
|
|
240
|
+
${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
|
|
241
|
+
<title>${ji(e)}</title>
|
|
242
|
+
<style>${_P}</style>
|
|
242
243
|
</head>
|
|
243
|
-
<body><main class="card">${
|
|
244
|
-
</html>`}function
|
|
245
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${
|
|
244
|
+
<body><main class="card">${t}</main></body>
|
|
245
|
+
</html>`}function Wy(e){let t=Math.max(1,Math.round(e.sinceMs/1000)),r=e.logTail?`<pre>${ji(e.logTail)}</pre>`:"",i=`
|
|
246
|
+
<div class="row"><div class="spinner"></div><h1>Starting ${ji(e.host)}…</h1></div>
|
|
246
247
|
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
247
248
|
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
248
|
-
<p>Booting for ${
|
|
249
|
-
${
|
|
250
|
-
<div class="row"><div class="dot"></div><h1>${
|
|
251
|
-
<p>${
|
|
252
|
-
${
|
|
253
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(
|
|
249
|
+
<p>Booting for ${t}s.</p>
|
|
250
|
+
${r}`;return new Response(Uy(`Starting ${e.host}`,i,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function Ky(e){let t=e.logTail?`<pre>${ji(e.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
|
|
251
|
+
<div class="row"><div class="dot"></div><h1>${ji(e.host)} failed to start</h1></div>
|
|
252
|
+
<p>${ji(e.error)}</p>
|
|
253
|
+
${t}
|
|
254
|
+
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(Uy(`${e.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var _P=`
|
|
254
255
|
:root { color-scheme: light dark }
|
|
255
256
|
* { box-sizing: border-box }
|
|
256
257
|
body {
|
|
@@ -276,63 +277,54 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
|
|
|
276
277
|
}
|
|
277
278
|
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
278
279
|
@keyframes spin { to { transform: rotate(360deg) } }
|
|
279
|
-
`;import{exec as
|
|
280
|
-
`),
|
|
280
|
+
`;import{exec as jP}from"node:child_process";import ka from"node:fs";import UP from"node:os";import Yy from"node:path";import*as Kr from"node:process";import{promisify as WP}from"node:util";function Hy(e){let t=e.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}async function zy(e){if(Kr.platform==="win32")throw Error("Administrator privileges required on Windows");if(yn()){let{stdout:i}=await Mn(e);return i}let t=pr(),r=e.replace(/'/g,"'\\''");try{if(t){let{stdout:i}=await Mn(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`);return Rf=!0,i}if(Rf)try{let{stdout:i}=await Mn(`sudo -n sh -c '${r}'`);return i}catch(i){m("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:i}=await Mn(`sudo -n sh -c '${r}'`);return Rf=!0,i}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(i){throw Error(`Failed to execute sudo command: ${i.message}`)}}function Na(e){let t=e.indexOf("#"),r=(t===-1?e:e.slice(0,t)).trim();if(!r)return null;let i=t===-1?"":e.slice(t+1).trim(),[n,...s]=r.split(/\s+/);if(!n||s.length===0)return null;let o=/^rpx(?::pid=(\d+))?$/.exec(i);return{address:n,names:s,comment:i,rpxPid:o?.[1]?Number.parseInt(o[1],10):null,rpxManaged:o!==null}}function Gy(e,t){let r=Na(e);return r!==null&&Oa.has(r.address)&&r.names.includes(t)}function HP(e,t){let r=new Set(t),i=new Set,n=e.split(`
|
|
281
|
+
`),s=[],o=0;while(o<n.length){let c=n[o];if(c.trim()===KP){let l=[],u=o+1;while(u<n.length){let h=n[u];if(h.trim()===""||h.trim().startsWith("#"))break;l.push(h),u++}let f=l.filter((h)=>{let d=Na(h),y=d!==null&&Oa.has(d.address)&&d.names.some((g)=>r.has(g));if(y){for(let g of d.names)if(r.has(g))i.add(g)}return!y});if(f.length>0||l.length===0)s.push(c,...f);o=u;continue}let a=Na(c);if(a?.rpxManaged&&Oa.has(a.address)&&a.names.some((l)=>r.has(l))){for(let l of a.names)if(r.has(l))i.add(l);o++;continue}s.push(c),o++}while(s.length>0&&s[s.length-1].trim()==="")s.pop();return{content:`${s.join(`
|
|
281
282
|
`)}
|
|
282
|
-
`,removed:[...
|
|
283
|
-
`)){let
|
|
283
|
+
`,removed:[...i]}}function VP(e,t){let r=[],i=new Set,n=[];for(let s of e.split(`
|
|
284
|
+
`)){let o=Na(s);if(o?.rpxManaged&&o.rpxPid!==null&&Oa.has(o.address)&&!t(o.rpxPid)){r.push(...o.names),i.add(o.rpxPid);continue}n.push(s)}while(n.length>0&&n[n.length-1].trim()==="")n.pop();return{content:`${n.join(`
|
|
284
285
|
`)}
|
|
285
|
-
`,removed:
|
|
286
|
-
`),
|
|
287
|
-
127.0.0.1 ${
|
|
288
|
-
::1 ${
|
|
289
|
-
`);try{await
|
|
290
|
-
`);return
|
|
291
|
-
`,"utf8")}async function
|
|
286
|
+
`,removed:r,stalePids:[...i]}}async function Af(e){try{return await ka.promises.readFile(ir,"utf-8")}catch{return m("hosts","Reading hosts file requires elevated permissions, using sudo",e),zy(`cat "${ir}"`)}}async function kf(e,t){let r=Yy.join(UP.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await ka.promises.writeFile(r,e,"utf8"),await zy(`cat "${r}" | tee "${ir}" > /dev/null`)}finally{await ka.promises.unlink(r).catch((i)=>{m("hosts",`Failed to remove temporary file: ${i}`,t)})}}async function In(e,t){let r=e.filter((n)=>!Hy(n)),i=e.filter((n)=>Hy(n));if(i.length>0)m("hosts",`Skipping /etc/hosts for loopback dev names: ${i.join(", ")}`,t);if(r.length===0)return;m("hosts",`Adding hosts: ${r.join(", ")}`,t),m("hosts",`Using hosts file at: ${ir}`,t);try{let n;try{n=await Af(t)}catch(l){throw console.log(" Could not read hosts file — skipping hosts setup"),m("hosts",`sudo read also failed: ${l}`,t),Error(`Cannot read hosts file: ${l}`)}let s=n.split(`
|
|
287
|
+
`),o=r.filter((l)=>!s.some((u)=>Gy(u,l)));if(o.length===0){m("hosts","All hosts already exist in hosts file",t);return}let c=Kr.pid,a=o.map((l)=>`
|
|
288
|
+
127.0.0.1 ${l} ${Vy}:pid=${c}
|
|
289
|
+
::1 ${l} ${Vy}:pid=${c}`).join(`
|
|
290
|
+
`);try{await kf(n+a,t),console.log(` Hosts updated: ${o.join(", ")}`)}catch(l){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),o.forEach((u)=>{console.log(` 127.0.0.1 ${u}`),console.log(` ::1 ${u}`)}),console.log(` Or run: sudo nano ${ir}`)}}catch(n){m("hosts",`Failed to manage hosts file: ${n.message}`,t)}}async function qy(e,t){m("hosts",`Removing hosts: ${e.join(", ")}`,t);try{let r;try{r=await Af(t)}catch(s){throw m("hosts",`sudo read also failed: ${s}`,t),Error(`Cannot read hosts file: ${s}`)}let{content:i,removed:n}=HP(r,e);if(n.length===0){m("hosts","No matching rpx-managed hosts found to remove",t);return}try{await kf(i,t),m("hosts",`Hosts removed successfully: ${n.join(", ")}`,t)}catch(s){m("hosts","Could not clean up hosts file automatically",t)}}catch(r){m("hosts",`Failed to clean up hosts file: ${r.message}`,t)}}async function _n(e,t){m("hosts",`Checking hosts: ${e}`,t);let r;try{r=await ka.promises.readFile(ir,"utf-8")}catch(n){m("hosts",`Error reading hosts file: ${n}`,t);try{let s=pr(),o;if(s)o=`echo '${s}' | sudo -S cat "${ir}" 2>/dev/null`;else o=`sudo -n cat "${ir}" 2>/dev/null || cat "${ir}" 2>/dev/null || echo ""`;let{stdout:c}=await Mn(o);r=c}catch(s){return m("hosts",`Cannot read hosts file, assuming entries don't exist: ${s}`,t),e.map(()=>!1)}}let i=r.split(`
|
|
291
|
+
`);return e.map((n)=>i.some((s)=>Gy(s,n)))}async function jn(e={}){let t=e.isAlive??ot,r;try{r=await Af(e.verbose)}catch(o){return m("hosts",`stale hosts GC: cannot read hosts file: ${o}`,e.verbose),[]}let{content:i,removed:n,stalePids:s}=VP(r,t);if(n.length===0)return[];try{return await kf(i,e.verbose),m("hosts",`stale hosts GC: removed ${n.join(", ")} (dead pid(s): ${s.join(", ")})`,e.verbose),[...new Set(n)]}catch(o){return m("hosts",`stale hosts GC: write failed: ${o}`,e.verbose),[]}}var Mn,ir,Vy="# rpx",KP="# Added by rpx",Oa,Rf=!1;var Of=Q(()=>{Wr();he();Mn=WP(jP);ir=Kr.platform==="win32"?Yy.join(Kr.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Oa=new Set(["127.0.0.1","::1"])});import*as Er from"node:fs/promises";import{homedir as YP}from"node:os";import*as Nf from"node:path";function Xy(){return Nf.join(YP(),".stacks","rpx")}function Df(e=Xy()){return Nf.join(e,zP)}async function Fa(e=Xy()){try{let t=await Er.readFile(Df(e),"utf8"),r=JSON.parse(t);if(r.version!==Da||!Array.isArray(r.resolvers))return null;return{version:Da,resolvers:r.resolvers.filter((i)=>typeof i==="string"),domains:Array.isArray(r.domains)?r.domains.filter((i)=>typeof i==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Qy(e,t){await Er.mkdir(e,{recursive:!0}),await Er.writeFile(Df(e),`${JSON.stringify(t,null,2)}
|
|
292
|
+
`,"utf8")}async function Ff(e){await Er.rm(Df(e),{force:!0})}function Zy(e){let t=e.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function qP(e){let t=Zy(e);if(!t)return null;let r=t.split(".");if(r.length<2)return null;let i=r[r.length-1];if(GP.has(i))return r.slice(-2).join(".");return t}function Bf(e){let t=new Set;for(let r of e){let i=qP(r);if(i)t.add(i)}return Array.from(t).sort()}function Lf(e){let t=new Set;for(let r of e){let i=Zy(r);if(i)t.add(i)}return Array.from(t).sort()}var Da=1,zP="dns-state.json",Jy,GP;var ew=Q(()=>{Jy=["com","test","dev","app","page","local","localhost","example","invalid"];GP=new Set(["test","localhost","local","example","invalid","internal","home","lan"])});var La={};Qf(La,{DNS_PORT:()=>Wn,RPX_RESOLVER_MARKER:()=>nw,contentLooksLikeRpxResolver:()=>uw,isDnsServerRunning:()=>ZP,isRpxDevelopmentDnsAnswering:()=>lw,reconcileStaleDevelopmentDns:()=>Vr,removeLegacyTldResolvers:()=>jf,removeResolver:()=>aR,resolverFilePath:()=>Ui,setupDevelopmentDns:()=>Uf,setupResolver:()=>sR,startDnsServer:()=>cw,stopDnsServer:()=>Mf,syncDevelopmentDnsFromRegistry:()=>Wi,tearDownDevelopmentDns:()=>Hr});import tw from"node:dgram";import*as rw from"node:fs/promises";import*as iw from"node:path";import*as nr from"node:process";function ow(e){return{id:e.readUInt16BE(0),flags:e.readUInt16BE(2),qdcount:e.readUInt16BE(4),ancount:e.readUInt16BE(6),nscount:e.readUInt16BE(8),arcount:e.readUInt16BE(10)}}function aw(e,t,r=0){let i=[],n=t,s=0;while(!0){if(n>=e.length||++s>128)break;let o=e[n];if(o===0){n++;break}if((o&192)===192){if(n+1>=e.length||r>=10)break;let c=e.readUInt16BE(n)&16383,{name:a}=aw(e,c,r+1);if(a)i.push(a);n+=2;break}if(n++,n+o>e.length)break;i.push(e.subarray(n,n+o).toString("ascii")),n+=o}return{name:i.join("."),newOffset:n}}function JP(e,t){let{name:r,newOffset:i}=aw(e,t),n=e.readUInt16BE(i),s=e.readUInt16BE(i+2);return{question:{name:r,type:n,class:s},newOffset:i+4}}function Un(e){let t=e.split("."),r=[];for(let i of t)r.push(Buffer.from([i.length])),r.push(Buffer.from(i,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function XP(e,t,r){let i=[],n=Buffer.alloc(12);n.writeUInt16BE(e,0),n.writeUInt16BE(33152,2),n.writeUInt16BE(1,4),n.writeUInt16BE(1,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),i.push(n),i.push(Un(t.name));let s=Buffer.alloc(4);s.writeUInt16BE(t.type,0),s.writeUInt16BE(t.class,2),i.push(s),i.push(Un(t.name));let o=Buffer.alloc(10);if(o.writeUInt16BE(t.type,0),o.writeUInt16BE(1,2),o.writeUInt32BE(300,4),t.type===1){o.writeUInt16BE(4,8),i.push(o);let c=r.split(".").map((a)=>Number.parseInt(a,10));i.push(Buffer.from(c))}else if(t.type===28)o.writeUInt16BE(16,8),i.push(o),i.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return n.writeUInt16BE(33155,2),n.writeUInt16BE(0,6),Buffer.concat([n,Un(t.name),s]);return Buffer.concat(i)}function QP(e,t){let r=[],i=Buffer.alloc(12);i.writeUInt16BE(e,0),i.writeUInt16BE(33155,2),i.writeUInt16BE(1,4),i.writeUInt16BE(0,6),i.writeUInt16BE(0,8),i.writeUInt16BE(0,10),r.push(i),r.push(Un(t.name));let n=Buffer.alloc(4);return n.writeUInt16BE(t.type,0),n.writeUInt16BE(t.class,2),r.push(n),Buffer.concat(r)}async function cw(e,t){if(nr.platform!=="darwin")return!1;let r=Lf(e);if(r.length===0)return!1;if(Qe){for(let i of r)Ba.add(i);return m("dns","DNS server already running — merged domains",t),!0}return Ba=new Set(r),new Promise((i)=>{Qe=tw.createSocket("udp4"),Qe.on("error",(n)=>{m("dns",`DNS server error: ${n.message}`,t),Qe?.close(),Qe=null,i(!1)}),Qe.on("message",(n,s)=>{try{let o=ow(n),{question:c}=JP(n,12);m("dns",`Query for ${c.name} type ${c.type} from ${s.address}`,t);let a=c.name.toLowerCase(),l=!1;for(let f of Ba)if(a===f||a.endsWith(`.${f}`)){l=!0;break}let u;if(l&&(c.type===1||c.type===28))u=XP(o.id,c,"127.0.0.1"),m("dns",`Responding with localhost for ${c.name}`,t);else u=QP(o.id,c),m("dns",`NXDOMAIN for ${c.name}`,t);Qe?.send(u,s.port,s.address)}catch(o){m("dns",`Error processing DNS query: ${o}`,t)}}),Qe.on("listening",()=>{let n=Qe?.address();m("dns",`DNS server listening on ${n?.address}:${n?.port}`,t),i(!0)});try{Qe.bind(Wn,"127.0.0.1")}catch(n){m("dns",`Failed to bind DNS server: ${n}`,t),i(!1)}})}function Mf(e){if(Qe)m("dns","Stopping DNS server",e),Qe.close(),Qe=null,Ba=new Set}function ZP(){return Qe!==null}async function lw(e,t=500){let r=e.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((i)=>{let n=tw.createSocket("udp4"),s=setTimeout(()=>{n.close(),i(!1)},t);n.on("message",(c)=>{clearTimeout(s),n.close();try{let a=ow(c);i(a.ancount>0)}catch{i(!1)}}),n.on("error",()=>{clearTimeout(s),n.close(),i(!1)});let o=eR(r,1);n.send(o,Wn,"127.0.0.1",(c)=>{if(c)clearTimeout(s),n.close(),i(!1)})})}function eR(e,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let i=Buffer.concat([Un(e),Buffer.from([0,t,0,1])]);return Buffer.concat([r,i])}function tR(){return`${nw}
|
|
292
293
|
nameserver 127.0.0.1
|
|
293
|
-
port ${
|
|
294
|
-
`}function
|
|
295
|
-
`)}finally{await
|
|
296
|
-
`),
|
|
297
|
-
`):B.ca}:null,T=!1,F=[];function E(_){for(let c0 of F)try{c0.kill(_)}catch{}}async function N(_){await N6(Y,_,G),E("SIGHUP")}let R=w.onDemandTls,V=R?.enabled?new b1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??_w.join(Y,"on-demand-certs"),initial:f,verbose:j,onCertAdded:(_)=>{if(xY()==="restart")K("on-demand","certificate installed; restarting supervised gateway to reload TLS",j),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else N(_)}}):null;await N6(Y,V?V.sniEntries():f,G);let L=await Tw(A,j);await n$({rpxDir:Y,verbose:j}).catch((_)=>{K("daemon",`DNS reconcile on start failed: ${_}`,j)}),await m1(L,{rpxDir:Y,verbose:j,ownerPid:y.pid}).catch((_)=>{K("daemon",`DNS setup on start failed: ${_}`,j)}),await kY(A,j).catch(()=>{}),await uY({verbose:j}).catch(()=>{});let q=_8((_)=>{m1(_,{rpxDir:Y,verbose:j,ownerPid:y.pid}).catch((c0)=>{K("daemon",`DNS sync on registry change failed: ${c0}`,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 y6(_,V,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,n=60000,a0=30000,Uw=0,l$=Date.now();function d1(){if(T)return;let _={...y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:j?"1":"0"},c0=Bun.spawn(LR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n1,pY){if(T)return;let rY=F.indexOf(n1);if(rY!==-1)F.splice(rY,1);let p$=Date.now();if(p$-l$>n)l$=p$,Uw=0;if(Uw++,Uw>D){H.error(`rpx: worker keeps exiting (code ${pY}); giving up after ${D} restarts in ${Math.round(n/1000)}s`);return}let Ow=Math.min(a0,100*2**Math.min(Uw,8));K("daemon",`worker exited (code ${pY}); respawning in ${Ow}ms (restart ${Uw}/${D})`,j),setTimeout(d1,Ow).unref?.()}});F.push(c0)}for(let _=0;_<Q;_++)d1();if(j)H.success(`rpx coordinator listening on https://${U}:${X} via ${Q} worker(s)${M?` (http→https on :${J})`:""}`),H.info(`pid file: ${z}`);let J$,i0=new Promise((_)=>{J$=_});async function Ww(){if(T)return i0;if(T=!0,clearInterval(C),q.close(),M?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(F.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),E("SIGKILL"),await d$({rpxDir:Y,verbose:j}).catch((_)=>{K("daemon",`DNS teardown failed: ${_}`,j)}),await g1(Y),await b0.unlink(dj(Y)).catch(()=>{}),j)H.info("rpx coordinator stopped");return J$(),i0}let v0=(_)=>{K("daemon",`coordinator received ${_}, shutting down`,j),Ww().catch(()=>{})};return y.once("SIGINT",v0),y.once("SIGTERM",v0),{stop:Ww,done:i0,httpsPort:X,httpPort:J,pidPath:z,ensureCert:(_)=>V?V.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function _R(){let w=y.execPath,$=_w.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function g8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await n$({rpxDir:$,verbose:Y}).catch((z)=>{K("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await V$($);if(A!==null&&Jw(A))return K("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)K("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await g1($);await b0.mkdir($,{recursive:!0});let X=w.spawnCommand??_R();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");K("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=H6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??y.cwd(),env:w.spawnEnv?{...y.env,...w.spawnEnv}:y.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let j=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,Q=Date.now()+j;while(Date.now()<Q){if(U)throw U;let z=await V$($);if(z!==null&&Jw(z))return K("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((f)=>setTimeout(f,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||!Jw(U)){if(U!==null)await g1($);return await n$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{y.kill(U,"SIGTERM")}catch(W){let Q=W.code;if(Q==="ESRCH")return await g1($),{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(!Jw(U))return K("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`);K("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{y.kill(U,"SIGKILL")}catch(W){let Q=W.code;if(Q==="EPERM")T$(`kill -KILL ${U}`);else if(Q!=="ESRCH")throw W}return await g1($),await d$({rpxDir:$,verbose:Y}).catch((W)=>{K("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 n$({rpxDir:$,verbose:w.verbose})}var MR=5000,v8,T6=!1;var b8=s(()=>{D$();Gj();Ej();Tj();y8();Hj();Rj();QU();n2();M8();N8();m$();Dj();mY();f0();v8=new Map});import{dirname as dR,join as nR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as lR}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 O$ from"node:process";import{EventEmitter as a6}from"node:events";import U$ from"node:process";import $Q from"node:process";import zJ from"node:process";import sY from"node:process";import t1 from"node:process";import XQ from"node:tty";import iG,{stdin as BM,stdout as GM}from"node:process";import UQ,{stdin as vG,stdout as cG}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(O$.env.DO_NOT_TRACK==="1"||O$.env.DO_NOT_TRACK==="true")return!1;if(O$.env.NO_TELEMETRY==="1"||O$.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:O$.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:O$.env.DO_NOT_TRACK==="1"||O$.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 wM=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 z of A[Q])Y[z]=W;if(J[j]&&A[J[j]])for(let z of A[J[j]])Y[z]=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 z=W.slice(2,Q),f=W.slice(Q+1);U(z,f)}else{let z=W.slice(2);if(z.startsWith("no-")){let B=z.slice(3);U(B,!1);continue}let f=J[z]||z;if(X.has(f)||X.has(z))U(z,!0);else{let B=w[j+1];if(B!==void 0&&!B.startsWith("-"))U(z,B),j++;else U(z,!0)}}}else if(W.startsWith("-")&&W.length>1){let Q=W.slice(1);for(let z=0;z<Q.length;z++){let f=Q[z],B=J[f]||f;if(z===Q.length-1&&!X.has(B)&&!X.has(f)){let G=w[j+1];if(G!==void 0&&!G.startsWith("-"))U(f,G),j++;else U(f,!0)}else U(f,!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}
|
|
294
|
+
port ${Wn}
|
|
295
|
+
`}function Ui(e){return iw.join(sw,e)}function uw(e){return e.includes("127.0.0.1")&&e.includes(String(Wn))}async function rR(e){try{return await rw.readFile(Ui(e),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function If(e){if(nr.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:i}=await Promise.resolve().then(() => (he(),Bi));if(!i()&&!r()){m("dns","Cannot flush DNS cache without SUDO_PASSWORD",e);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),m("dns","DNS cache flushed",e)}catch(n){m("dns",`Could not flush DNS cache: ${n}`,e)}}function fw(e){if(!/^[a-z0-9.-]+$/.test(e))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(e)}`)}async function iR(e,t){fw(e);let{execSudoSync:r}=await Promise.resolve().then(() => (he(),Bi)),i=tR().replace(/\n/g,"\\n"),n=`bash -c 'mkdir -p ${sw} && printf "%b" "${i}" > ${Ui(e)}'`;r(n),m("dns",`Created ${Ui(e)}`,t)}async function nR(e,t){fw(e);let{execSudoSync:r}=await Promise.resolve().then(() => (he(),Bi));r(`rm -f ${Ui(e)}`),m("dns",`Removed ${Ui(e)}`,t)}async function sR(e,t){return Uf({domains:t??[],verbose:e})}async function oR(e,t){if(nr.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:i}=await Promise.resolve().then(() => (he(),Bi));if(!i()&&!r())return m("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let n of e)await iR(n,t);return await If(t),!0}catch(n){return m("dns",`Failed to create resolver file: ${n}`,t),!1}}async function _f(e,t){if(nr.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:i}=await Promise.resolve().then(() => (he(),Bi));if(!i()&&!r())return;try{for(let n of e)await nR(n,t);await If(t)}catch(n){m("dns",`Failed to remove resolver files: ${n}`,t)}}async function jf(e){if(nr.platform!=="darwin")return[];let t=[];for(let r of Jy){let i=await rR(r);if(i&&uw(i))await _f([r],e),t.push(r)}return t}async function Uf(e){let t=e.rpxDir??Pe(),r=Lf(e.domains);if(r.length===0)return!1;let i=Bf(r),n=await cw(r,e.verbose);if(!n){let c=r[0];if(c&&await lw(c))n=!0;else m("dns","Dev DNS server not available on 127.0.0.1:15353",e.verbose)}if(!n)return!1;if(!await oR(i,e.verbose))return!1;let o={version:Da,resolvers:i,domains:r,ownerPid:e.ownerPid??nr.pid,updatedAt:new Date().toISOString()};return await Qy(t,o),!0}async function Wi(e,t={}){let r=e.map((a)=>a.to).filter(Boolean),i=t.rpxDir??Pe(),n=Bf(r),c=((await Fa(i))?.resolvers??[]).filter((a)=>!n.includes(a));if(c.length>0)await _f(c,t.verbose);if(n.length===0){Mf(t.verbose),await Ff(i);return}await Uf({domains:r,rpxDir:i,verbose:t.verbose,ownerPid:t.ownerPid??nr.pid})}async function Hr(e={}){let t=e.rpxDir??Pe();Mf(e.verbose);let i=(await Fa(t))?.resolvers??[];await _f(i,e.verbose),await jf(e.verbose),await Ff(t)}async function aR(e){await Hr({verbose:e})}async function Vr(e={}){let t=e.rpxDir??Pe(),r=await Fa(t),i=r?.ownerPid!=null&&ot(r.ownerPid);if(r&&!i){m("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,e.verbose),await Hr(e);return}let n=await jf(e.verbose);if(n.length>0)m("dns",`reconcile: removed legacy TLD resolvers: ${n.join(", ")}`,e.verbose);await If(e.verbose)}var Wn=15353,nw="# managed-by: rpx",sw="/etc/resolver",Qe=null,Ba;var Kn=Q(()=>{Ma();ew();Wr();he();Ba=new Set});import{spawn as gw}from"node:child_process";import*as _e from"node:fs/promises";import{homedir as pw}from"node:os";import*as Ot from"node:path";import*as E from"node:process";function Pe(){return Ot.join(pw(),".stacks","rpx")}function Pr(e=Pe()){return Ot.join(e,"daemon.pid")}async function Tr(e=Pe()){try{let t=await _e.readFile(Pr(e),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Ua(e=Pe()){let t=await Tr(e);return t!==null&&ot(t)}async function yw(e=Pe()){await _e.mkdir(e,{recursive:!0});let t=Pr(e);while(!0){try{let i=await _e.open(t,"wx");try{await i.write(`${E.pid}
|
|
296
|
+
`)}finally{await i.close()}return t}catch(i){if(i.code!=="EEXIST")throw i}let r=await Tr(e);if(r!==null&&ot(r))throw Error(`rpx daemon already running (pid=${r})`);await _e.unlink(t).catch(()=>{})}}async function Ki(e=Pe()){await _e.unlink(Pr(e)).catch(()=>{})}function ja(e){for(let[t,r]of _a)if(!e.has(t))Mi(r),_a.delete(t)}function lR(e,t){let r=fy(t??"localhost:1");if(e.upstreams.length!==r.length)return!1;return e.upstreams.every((i,n)=>i.url===r[n])}function ww(e){let t=e.cleanUrls??!1,r=rr(e.path),i=Tn(e.auth);if(e.static)return{static:ba(e.static,t),cleanUrls:t,basePath:r,auth:i};let n=e.from??"localhost:1",s=Ir(n),o=new URL(s.startsWith("http")?s:`http://${s}`),c=_a.get(e.id);if(c&&!lR(c,n))Mi(c),c=void 0;if(!c)c=xn(n,e.loadBalancer),Sn(c),_a.set(e.id,c);return{sourceHost:o.host,upstreamPool:c,cleanUrls:t,changeOrigin:e.changeOrigin??!1,pathRewrites:e.pathRewrites,basePath:r,auth:i}}function uR(e){return e.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??e[0]??"rpx.localhost"}async function Ia(e,t,r=[],i=!1){let n=await wt(t,e.verbose),s=[...new Set([...n.map((u)=>u.to).filter(Boolean),...r])],o=uR(s),c=[...new Set([o,...s,"rpx.localhost"])],a=oy(s,o,e.verbose);if(typeof e.https==="object"&&typeof a.https==="object")a.https={...a.https,...e.https};let l=await xr(a);if(l&&(i||!gu(lf,c)))m("daemon",`regenerating shared cert for host(s): ${c.join(", ")}`,e.verbose),uf(),l=null;if(!l)m("daemon","no usable cert on disk, generating one via tlsx",e.verbose),await bn({...a,forceRegenerate:!0}),l=await xr(a);if(!l)throw Error("failed to bootstrap TLS for rpx daemon");return l}async function fR(e,t,r,i){let n=E.env.SUDO_PASSWORD,s=E.env.HOME??pw(),o=[E.execPath,...E.argv.slice(1)],c=[`HOME=${s}`,`PATH=${E.env.PATH??""}`];if(i)c.push("RPX_VERBOSE=1");for(let[y,g]of Object.entries(E.env))if(g!==void 0&&y!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(y))c.push(`${y}=${g}`);let a=n?["-S","-p","","env",...c,...o]:["-n","env",...c,...o];m("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,i);let l=gw("sudo",a,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,f=null;if(l.once("error",(y)=>{u=y}),l.once("exit",(y)=>{f=y??0}),n&&l.stdin)l.stdin.write(`${n}
|
|
297
|
+
`),l.stdin.end();l.unref();let h=Pr(e),d=Date.now()+15000;while(Date.now()<d){if(u)throw u;let y=await Tr(e);if(y!==null&&ot(y)){if(i)x.success(`rpx daemon elevated to root (pid=${y}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:h,done:Promise.resolve(),stop:async()=>{try{E.kill(y,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(f!==null&&f!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${f}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((g)=>setTimeout(g,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${e})`)}function Wf(){if(hw)return;hw=!0,E.on("uncaughtException",(e)=>{x.error(`rpx daemon: uncaught exception (continuing): ${e?.stack??e}`)}),E.on("unhandledRejection",(e)=>{x.error(`rpx daemon: unhandled rejection (continuing): ${e}`)})}function vw(e,t,r){let i;try{i=new URL(e.url)}catch{return new Response("Bad Request",{status:400})}let n=(e.headers.get("host")??i.hostname).split(":")[0];if(i.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let s=t.challengeStore.handlePath(i.pathname);if(s!==void 0)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(r){let s=xa(r,i.pathname);if(s!=null)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(n))t.ensureCert(n).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${n}${i.pathname}${i.search}`}})}async function bw(e={}){Wf();let t=e.verbose??!1,r=e.rpxDir??Pe(),i=e.registryDir??Ot.join(r,"registry.d"),n=e.httpsPort??443,s=e.httpPort??80,o=e.hostname??"::",c=e.hostname==null,a=e.gcIntervalMs??cR;if(E.env.RPX_DAEMON_WORKER==="1")return mR({rpxDir:E.env.RPX_WORKER_RPXDIR??r,registryDir:E.env.RPX_WORKER_REGISTRYDIR??i,httpsPort:Number.parseInt(E.env.RPX_WORKER_HTTPSPORT??"",10)||n,hostname:E.env.RPX_WORKER_HOSTNAME??o,verbose:E.env.RPX_WORKER_VERBOSE==="1"||t});let l=n>0&&n<1024||s>0&&s<1024,u=typeof E.getuid==="function"&&E.getuid()===0;if(E.platform!=="win32"&&l&&!u)return fR(r,n,s,t);let f=Math.max(1,e.workers??(Number.parseInt(E.env.RPX_WORKERS??"",10)||1));if(f>1){if(e.onDemandSites?.enabled)x.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return gR(e,{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:t,gcIntervalMs:a,workers:f})}let h=await yw(r),d=new Map,y=(C,N)=>On(d,C,N);function g(C){d=kn(C.map((Ze)=>({host:Ze.to,path:Ze.path,route:ww(Ze)}))),ja(new Set(C.map((Ze)=>Ze.id)));let N=Array.from(d.keys());m("daemon",`routing table now covers ${N.length} host(s): ${N.join(", ")||"<empty>"}`,t)}await Bn(i,t).catch((C)=>{m("daemon",`initial gc failed: ${C}`,t)}),await jn({verbose:t}).catch((C)=>{m("daemon",`stale hosts GC on start failed: ${C}`,t)});let p=await wt(i,t);g(p),await Vr({rpxDir:r,verbose:t}).catch((C)=>{m("daemon",`DNS reconcile on start failed: ${C}`,t)}),await Wi(p,{rpxDir:r,verbose:t,ownerPid:E.pid}).catch((C)=>{m("daemon",`DNS setup on start failed: ${C}`,t)});let w=[];if(e.productionCerts){if(w=await Dn(e.productionCerts,t),t&&w.length>0)x.info(`SNI: serving ${w.length} real cert(s): ${w.map((C)=>C.serverName).join(", ")}`)}let b=new Set,P=null,R;if(e.onDemandSites?.enabled){if(P=new Pf({resolver:sl(e.onDemandSites),registryDir:i,rpxDir:r,verbose:t,startupTimeoutMs:e.onDemandSites.startupTimeoutMs,isHostRoutable:(C)=>yf(d,C)!==void 0,onSiteActivating:(C)=>{Gn(C)}}),R=async(C)=>{let N=await P.onRequest(C);switch(N.kind){case"ready":return{retry:!0};case"starting":return Wy({host:N.host,sinceMs:N.sinceMs,logTail:N.logTail});case"failed":return Ky({host:N.host,error:N.error,logTail:N.logTail});case"unknown":default:return}},t)x.info("rpx: on-demand sites enabled")}let v=Rn(y,t,R),T=An(t),S=null;if(w.length===0)S=await Ia(e,i);let D=e.onDemandTls,W=D?.enabled?new Ii({config:D,certsDir:D.certsDir??e.productionCerts?.certsDir??Ot.join(r,"on-demand-certs"),initial:w,verbose:t,onCertAdded:(C)=>{if(Fn()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>E.kill(E.pid,"SIGTERM"),10).unref();else O(C)}}):null;function Xe(C){if(C.length>0)return jr(C.map((N)=>({serverName:N.serverName,cert:N.cert,key:N.key})));return jr({key:S.key,cert:S.cert,ca:S.ca,requestCert:!1,rejectUnauthorized:!1})}function at(C){try{return Bun.serve(C)}catch(N){let Ze=N instanceof Error?N.message:String(N),Yi=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(Ze);if(!c||C.hostname!=="::"||!Yi)throw N;return m("daemon",`no IPv6 on this host (${Ze}); binding 0.0.0.0`,e.verbose),Bun.serve({...C,hostname:"0.0.0.0"})}}function Yr(C){return at({port:n,hostname:o,reusePort:wn(),tls:Xe(C),fetch(N,Ze){return v(N,Ze)},websocket:T,error(N){return m("daemon",`https server error: ${N}`,t),new Response(`Server Error: ${N.message}`,{status:500})}})}let Hi=(C)=>[...new Set(C.map((N)=>N.to).filter(Boolean))],sr=(C)=>{if(!S)return w;return sy([...Hi(C),...b,"rpx.localhost"],S)},Ie=Yr(W?W.sniEntries():w.length>0?w:sr(p)),ct=null,Ue=!1;async function O(C){if(At)return;if(ct=C,Ue)return;Ue=!0;try{while(!At&&ct){let N=ct;ct=null,m("daemon",`rebuilding :443 with ${N.length} SNI cert(s)`,t),Ie.stop(!1);let Ze,Yi=!1,Xf=60,Mw=500;for(let ic=0;!At&&!Yi;ic++)try{Ie=Yr(N),Yi=!0;break}catch(Iw){if(Ze=Iw,ic>=Xf)break;await new Promise((_w)=>setTimeout(_w,Math.min(25*2**Math.min(ic,4),Mw)))}if(!Yi)x.error(`rpx: CRITICAL — could not rebind :443 after ${Xf} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Ze?.message}`)}}finally{Ue=!1}}let We=null;if(s>0)We=at({port:s,hostname:o,fetch(C){return vw(C,W,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)x.success(`rpx daemon listening on https://${o}:${n}${We?` (http→https on :${s})`:""}`),x.info(`pid file: ${h}`),x.info(`registry: ${i}`);async function Vi(C){if(At||w.length>0||W||!S)return;try{S=await Ia(e,i,[...b]),await O(sr(C))}catch(N){m("daemon",`TLS sync on registry change failed: ${N}`,t)}}async function Gn(C){if(At||w.length>0||W||!S||!C)return;if(b.has(C))return;b.add(C);try{S=await Ia(e,i,[...b],!0);let N=await wt(i,t);await O(sr(N))}catch(N){m("daemon",`dev cert refresh for ${C} failed: ${N}`,t)}}let qn=Aa((C)=>{g(C),Vi(C),Wi(C,{rpxDir:r,verbose:t,ownerPid:E.pid}).catch((N)=>{m("daemon",`DNS sync on registry change failed: ${N}`,t)})},{dir:i,verbose:t}),zr=setInterval(()=>{Bn(i,t).then((C)=>{if(C>0)m("daemon",`gc reaped ${C} stale entries`,t)}).catch((C)=>{m("daemon",`periodic gc failed: ${C}`,t)}),jn({verbose:t}).then((C)=>{if(C.length>0)m("daemon",`gc reaped stale hosts entries: ${C.join(", ")}`,t)}).catch((C)=>{m("daemon",`periodic hosts gc failed: ${C}`,t)})},a);if(typeof zr.unref==="function")zr.unref();let At=!1,tc,rc=new Promise((C)=>{tc=C});async function qf(){if(At)return rc;if(At=!0,clearInterval(zr),qn.close(),await P?.stopAll().catch((C)=>{m("daemon",`site supervisor stopAll failed: ${C}`,t)}),Ie.stop(!1),We?.stop(!1),await Hr({rpxDir:r,verbose:t}).catch((C)=>{m("daemon",`DNS teardown failed: ${C}`,t)}),ja(new Set),await Ki(r),t)x.info("rpx daemon stopped");return tc(),rc}let Jf=(C)=>{m("daemon",`received ${C}, shutting down`,t),qf().catch(()=>{})};return E.once("SIGINT",Jf),E.once("SIGTERM",Jf),{stop:qf,done:rc,httpsPort:typeof Ie.port==="number"?Ie.port:n,httpPort:We&&typeof We.port==="number"?We.port:s,pidPath:h,ensureCert:(C)=>W?W.ensureCert(C):Promise.resolve(!1),listSites:()=>P?.list()??[]}}function Kf(e){return Ot.join(e,"cluster-sni.json")}async function dw(e,t,r){let i=Kf(e),n=`${i}.${E.pid}.tmp`;await _e.writeFile(n,JSON.stringify({sni:t,dev:r}),"utf8"),await _e.rename(n,i)}async function mw(e){try{return JSON.parse(await _e.readFile(Kf(e),"utf8"))}catch{return{sni:[],dev:null}}}function hR(e){if(e.sni.length>0)return jr(e.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(e.dev)return jr({key:e.dev.key,cert:e.dev.cert,ca:e.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function dR(){let e=E.execPath,t=E.env.RPX_WORKER_BIN;if(t)return[e,t,"daemon:start"];let r=Ot.basename(e).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&E.argv[1])return[e,E.argv[1],"daemon:start"];return[e,"daemon:start"]}async function mR(e){Wf();let{rpxDir:t,registryDir:r,httpsPort:i,hostname:n,verbose:s}=e,o=new Map,c=(T,S)=>On(o,T,S),a=(T)=>{o=kn(T.map((S)=>({host:S.to,path:S.path,route:ww(S)}))),ja(new Set(T.map((S)=>S.id)))};a(await wt(r,s));let l=Rn(c,s),u=An(s),f=!1,h=(T)=>Bun.serve({port:i,hostname:n,reusePort:!0,tls:hR(T),fetch(S,D){return l(S,D)},websocket:u,error(S){return m("daemon",`worker https error: ${S}`,s),new Response(`Server Error: ${S.message}`,{status:500})}}),d=h(await mw(t));async function y(){if(f)return;let T=await mw(t),S=null;for(let W=0;W<20&&!f;W++)try{S=h(T);break}catch{await new Promise((Xe)=>setTimeout(Xe,25))}if(!S){m("daemon","worker reloadTls: could not bind new listener; keeping current",s);return}let D=d;d=S,D.stop(!1)}let g=Aa((T)=>a(T),{dir:r,verbose:s}),p=()=>{y().catch(()=>{})};E.on("SIGHUP",p);let w=()=>{let T=E.removeListener??E.off;if(typeof T==="function")T.call(E,"SIGHUP",p)},b,P=new Promise((T)=>{b=T});async function R(){if(f)return P;return f=!0,w(),g.close(),d.stop(!1),ja(new Set),b(),P}let v=()=>{R().then(()=>E.exit(0)).catch(()=>E.exit(0))};if(E.once("SIGTERM",v),E.once("SIGINT",v),s)x.success(`rpx worker (pid ${E.pid}) serving :${i}`);return{stop:R,done:P,httpsPort:typeof d.port==="number"?d.port:i,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function gR(e,t){Wf();let{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:c,gcIntervalMs:a,workers:l}=t,u=await yw(r),f=[];if(e.productionCerts)f=await Dn(e.productionCerts,c);let h=null;if(f.length===0)h=await Ia(e,i);let d=h?{key:h.key,cert:h.cert,ca:Array.isArray(h.ca)?h.ca.join(`
|
|
298
|
+
`):h.ca}:null,y=!1,g=[];function p(O){for(let We of g)try{We.kill(O)}catch{}}async function w(O){await dw(r,O,d),p("SIGHUP")}let b=e.onDemandTls,P=b?.enabled?new Ii({config:b,certsDir:b.certsDir??e.productionCerts?.certsDir??Ot.join(r,"on-demand-certs"),initial:f,verbose:c,onCertAdded:(O)=>{if(Fn()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",c),setTimeout(()=>E.kill(E.pid,"SIGTERM"),10).unref();else w(O)}}):null;await dw(r,P?P.sniEntries():f,d);let R=await wt(i,c);await Vr({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS reconcile on start failed: ${O}`,c)}),await Wi(R,{rpxDir:r,verbose:c,ownerPid:E.pid}).catch((O)=>{m("daemon",`DNS setup on start failed: ${O}`,c)}),await Bn(i,c).catch(()=>{}),await jn({verbose:c}).catch(()=>{});let v=Aa((O)=>{Wi(O,{rpxDir:r,verbose:c,ownerPid:E.pid}).catch((We)=>{m("daemon",`DNS sync on registry change failed: ${We}`,c)})},{dir:i,verbose:c}),T=setInterval(()=>{Bn(i,c).catch(()=>{}),jn({verbose:c}).catch(()=>{})},a);T.unref?.();let S=null;if(s>0)S=Bun.serve({port:s,hostname:o,fetch(O){return vw(O,P,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,W=60000,Xe=30000,at=0,Yr=Date.now();function Hi(){if(y)return;let O={...E.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:i,RPX_WORKER_HTTPSPORT:String(n),RPX_WORKER_HOSTNAME:o,RPX_WORKER_VERBOSE:c?"1":"0"},We=Bun.spawn(dR(),{env:O,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(Vi,Gn){if(y)return;let qn=g.indexOf(Vi);if(qn!==-1)g.splice(qn,1);let zr=Date.now();if(zr-Yr>W)Yr=zr,at=0;if(at++,at>D){x.error(`rpx: worker keeps exiting (code ${Gn}); giving up after ${D} restarts in ${Math.round(W/1000)}s`);return}let At=Math.min(Xe,100*2**Math.min(at,8));m("daemon",`worker exited (code ${Gn}); respawning in ${At}ms (restart ${at}/${D})`,c),setTimeout(Hi,At).unref?.()}});g.push(We)}for(let O=0;O<l;O++)Hi();if(c)x.success(`rpx coordinator listening on https://${o}:${n} via ${l} worker(s)${S?` (http→https on :${s})`:""}`),x.info(`pid file: ${u}`);let sr,Ie=new Promise((O)=>{sr=O});async function ct(){if(y)return Ie;if(y=!0,clearInterval(T),v.close(),S?.stop(!1),p("SIGTERM"),await Promise.race([Promise.all(g.map((O)=>O.exited)),new Promise((O)=>setTimeout(O,3000))]),p("SIGKILL"),await Hr({rpxDir:r,verbose:c}).catch((O)=>{m("daemon",`DNS teardown failed: ${O}`,c)}),await Ki(r),await _e.unlink(Kf(r)).catch(()=>{}),c)x.info("rpx coordinator stopped");return sr(),Ie}let Ue=(O)=>{m("daemon",`coordinator received ${O}, shutting down`,c),ct().catch(()=>{})};return E.once("SIGINT",Ue),E.once("SIGTERM",Ue),{stop:ct,done:Ie,httpsPort:n,httpPort:s,pidPath:u,ensureCert:(O)=>P?P.ensureCert(O):Promise.resolve(!1),listSites:()=>[]}}function pR(){let e=E.execPath,t=Ot.basename(e).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&E.argv[1])return[e,E.argv[1],"daemon:start"];return[e,"daemon:start"]}async function Wa(e={}){let t=e.rpxDir??Pe(),r=e.verbose??!1;await Vr({rpxDir:t,verbose:r}).catch((u)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let i=await Tr(t);if(i!==null&&ot(i))return m("daemon",`ensureDaemonRunning: already running pid=${i}`,r),{pid:i,spawned:!1};if(i!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${i}`,r),await Ki(t);await _e.mkdir(t,{recursive:!0});let n=e.spawnCommand??pR();if(n.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${n.join(" ")}`,r);let s=gw(n[0],n.slice(1),{detached:!0,stdio:"ignore",cwd:e.spawnCwd??E.cwd(),env:e.spawnEnv?{...E.env,...e.spawnEnv}:E.env});s.unref();let o=null;s.once("error",(u)=>{o=u});let c=e.startupTimeoutMs??5000,a=e.pollIntervalMs??50,l=Date.now()+c;while(Date.now()<l){if(o)throw o;let u=await Tr(t);if(u!==null&&ot(u))return m("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise((f)=>setTimeout(f,a))}if(o)throw o;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${t})`)}async function $w(e={}){let t=e.rpxDir??Pe(),r=e.verbose??!1,i=e.timeoutMs??5000,n=e.pollIntervalMs??50,s=e.forceAfterTimeout??!0,o=await Tr(t);if(o===null||!ot(o)){if(o!==null)await Ki(t);return await Vr({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:o,forced:!1}}try{E.kill(o,"SIGTERM")}catch(a){let l=a.code;if(l==="ESRCH")return await Ki(t),{stopped:!1,pid:o,forced:!1};if(l==="EPERM")yr(`kill -TERM ${o}`);else throw a}let c=Date.now()+i;while(Date.now()<c){if(!ot(o))return m("daemon",`daemon pid=${o} stopped cleanly`,r),{stopped:!0,pid:o,forced:!1};await new Promise((a)=>setTimeout(a,n))}if(!s)throw Error(`rpx daemon (pid=${o}) did not exit within ${i}ms`);m("daemon",`daemon pid=${o} did not exit, escalating to SIGKILL`,r);try{E.kill(o,"SIGKILL")}catch(a){let l=a.code;if(l==="EPERM")yr(`kill -KILL ${o}`);else if(l!=="ESRCH")throw a}return await Ki(t),await Hr({rpxDir:t,verbose:r}).catch((a)=>{m("daemon",`DNS teardown after SIGKILL: ${a}`,r)}),{stopped:!0,pid:o,forced:!0}}async function xw(e={}){let t=e.rpxDir??Pe();if(await Ua(t))return;await Vr({rpxDir:t,verbose:e.verbose})}var cR=5000,_a,hw=!1;var Ma=Q(()=>{Nr();ff();gf();pf();Ca();vf();bf();ol();jy();$a();ya();Wr();Of();Kn();he();_a=new Map});import{dirname as kR,join as OR}from"node:path";import*as Me from"node:process";import{fileURLToPath as NR}from"node:url";import{existsSync as Hw}from"node:fs";import nc from"node:fs/promises";import Zf from"node:os";import sc from"node:path";import Rr from"node:process";import{EventEmitter as Vw}from"node:events";import or from"node:process";import eh from"node:process";import cc from"node:process";import Xn from"node:process";import qi from"node:process";import nh from"node:tty";import Dv,{stdin as ZR,stdout as eA}from"node:process";class sh{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let e=Zf.homedir(),t=sc.join(e,".config","clapp");this.configPath=sc.join(t,"telemetry.json")}async isEnabled(){if(Rr.env.DO_NOT_TRACK==="1"||Rr.env.DO_NOT_TRACK==="true")return!1;if(Rr.env.NO_TELEMETRY==="1"||Rr.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let e=await this.loadConfig();if(e.enabled=!0,!e.userId)e.userId=this.generateUserId();await this.saveConfig(e)}async disable(){let e=await this.loadConfig();e.enabled=!1,await this.saveConfig(e)}async track(e,t){if(!await this.isEnabled())return;let i={event:e,...t,timestamp:Date.now(),platform:Zf.platform(),nodeVersion:Rr.version};if(this.events.push(i),this.events.length>=10)await this.send()}async trackCommand(e,t){await this.track("command",{command:e,duration:t})}async trackError(e,t){await this.track("error",{error:e,command:t})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let t=await this.loadConfig();return t.lastSent=Date.now(),await this.saveConfig(t),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let t=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(t),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(e){return new Promise((t)=>setTimeout(t,e))}async status(){let e=await this.loadConfig();return{enabled:e.enabled,doNotTrack:Rr.env.DO_NOT_TRACK==="1"||Rr.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:e.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(Hw(this.configPath)){let e=await nc.readFile(this.configPath,"utf-8");return this.config=JSON.parse(e),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(e){this.config=e;try{let t=sc.dirname(this.configPath);await nc.mkdir(t,{recursive:!0}),await nc.writeFile(this.configPath,JSON.stringify(e,null,2),"utf-8")}catch{}}generateUserId(){let e=Math.random().toString(36).substring(2,15),t=Date.now().toString(36);return`${e}-${t}`}}var jR=new sh;function Yw(e,t={}){let r={_:[]},i=t.alias||{},n=new Set(t.boolean||[]),s={};for(let c of Object.keys(i))for(let a of i[c])s[a]=c;for(let c of n)if(i[c])for(let a of i[c])n.add(a);function o(c,a){let l=s[c]||c;if(r[l]=a,i[l])for(let u of i[l])r[u]=a;if(s[c]&&i[s[c]])for(let u of i[s[c]])r[u]=a;r[c]=a}for(let c=0;c<e.length;c++){let a=e[c];if(a==="--"){r._.push(...e.slice(c+1));break}if(a.startsWith("--")){let l=a.indexOf("=");if(l!==-1){let u=a.slice(2,l),f=a.slice(l+1);o(u,f)}else{let u=a.slice(2);if(u.startsWith("no-")){let h=u.slice(3);o(h,!1);continue}let f=s[u]||u;if(n.has(f)||n.has(u))o(u,!0);else{let h=e[c+1];if(h!==void 0&&!h.startsWith("-"))o(u,h),c++;else o(u,!0)}}}else if(a.startsWith("-")&&a.length>1){let l=a.slice(1);for(let u=0;u<l.length;u++){let f=l[u],h=s[f]||f;if(u===l.length-1&&!n.has(h)&&!n.has(f)){let d=e[c+1];if(d!==void 0&&!d.startsWith("-"))o(f,d),c++;else o(f,!0)}else o(f,!0)}}else r._.push(a)}return r}function ac(e){return e.replace(/[<[].+/,"").trim()}function zw(e){let t=/<([^>]+)>/g,r=/\[([^\]]+)\]/g,i=[],n=(c)=>{let a=!1,l=c[1];if(l.startsWith("..."))l=l.slice(3),a=!0;return{required:c[0].startsWith("<"),value:l,variadic:a}},s;while(s=t.exec(e))i.push(n(s));let o;while(o=r.exec(e))i.push(n(o));return i}function Gw(e){let t={alias:{},boolean:[]};for(let[r,i]of e.entries()){if(i.names.length>1)t.alias[i.names[0]]=i.names.slice(1);if(i.isBoolean)if(i.negated){if(!e.some((s,o)=>o!==r&&s.names.some((c)=>i.names.includes(c))&&typeof s.required==="boolean"))t.boolean.push(i.names[0])}else t.boolean.push(i.names[0])}return t}function th(e){return e.reduce((t,r)=>t.length>=r.length?t:r,"")}function oc(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}function qw(e){return e.replace(/([a-z])-([a-z])/g,(t,r,i)=>r+i.toUpperCase())}function Jw(e,t,r){let i=0,n=t.length,s=e,o;for(;i<n;++i)o=s[t[i]],s=s[t[i]]=i===n-1?r:o!=null?o:!!~t[i+1].indexOf(".")||!(+t[i+1]>-1)?{}:[]}function Xw(e,t){for(let r of Object.keys(t)){let i=t[r];if(i.shouldTransform){if(e[r]=Array.prototype.concat.call([],e[r]),typeof i.transformFunction==="function")e[r]=e[r].map(i.transformFunction)}}}function Qw(e){let t=/([^\\/]+)$/.exec(e);return t?t[1]:""}function oh(e){return e.split(".").map((t,r)=>r===0?qw(t):t).join(".")}class Jn extends Error{exitCode=2;isUsageError=!0;constructor(e){super(e);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(e).stack}format(e=!1){if(e&&this.stack)return`${this.message}
|
|
298
299
|
|
|
299
300
|
Stack trace:
|
|
300
|
-
${this.stack}`;return this.message}}function
|
|
301
|
-
`);let
|
|
301
|
+
${this.stack}`;return this.message}}function Zw(){let{env:e}=eh,{TERM:t,TERM_PROGRAM:r}=e;if(eh.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||r==="Terminus-Sublime"||r==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Qn="\x1B",ue=`${Qn}[`;var rh={to(e,t){if(!t)return`${ue}${e+1}G`;return`${ue}${t+1};${e+1}H`},move(e,t){let r="";if(e<0)r+=`${ue}${-e}D`;else if(e>0)r+=`${ue}${e}C`;if(t<0)r+=`${ue}${-t}A`;else if(t>0)r+=`${ue}${t}B`;return r},up:(e=1)=>`${ue}${e}A`,down:(e=1)=>`${ue}${e}B`,forward:(e=1)=>`${ue}${e}C`,backward:(e=1)=>`${ue}${e}D`,nextLine:(e=1)=>`${ue}E`.repeat(e),prevLine:(e=1)=>`${ue}F`.repeat(e),left:`${ue}G`,hide:`${ue}?25l`,show:`${ue}?25h`,save:`${Qn}7`,restore:`${Qn}8`};var HR={screen:`${ue}2J`,up:(e=1)=>`${ue}1J`.repeat(e),down:(e=1)=>`${ue}J`.repeat(e),line:`${ue}2K`,lineEnd:`${ue}K`,lineStart:`${ue}1K`,lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?rh.up():"");if(e)t+=rh.left;return t}},VR={screen:`${Qn}c`};function ev(e,t){let r=[];for(let i=0;i<=t.length;i++)r[i]=[i];for(let i=0;i<=e.length;i++)r[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=e.length;n++)if(t.charAt(i-1)===e.charAt(n-1))r[i][n]=r[i-1][n-1];else r[i][n]=Math.min(r[i-1][n-1]+1,r[i][n-1]+1,r[i-1][n]+1);return r[t.length][e.length]}function ah(e,t,r=2,i=3){return t.map((n)=>({cmd:n,distance:ev(e,n)})).filter(({distance:n})=>n<=r).sort((n,s)=>n.distance-s.distance).slice(0,i).map(({cmd:n})=>n)}class ch{rawName;description;name;names;isBoolean;required;config;negated;constructor(e,t,r){if(this.rawName=e,this.description=t,this.config=Object.assign({},r),e=e.replace(/\.\*/g,""),this.negated=!1,this.names=ac(e).split(",").map((i)=>{let n=i.trim().replace(/^-{1,2}/,"");if(n.startsWith("no-"))this.negated=!0,n=n.replace(/^no-/,"");return oh(n)}).sort((i,n)=>i.length>n.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(e.includes("<"))this.required=!0;else if(e.includes("["))this.required=!1;else this.isBoolean=!0}}var zR=cc.argv,tv=`${cc.platform}-${cc.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,ih=Xn.argv,rv=`${Xn.platform}-${Xn.arch} node-${Xn.version}`;class lc{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(e,t,r,i){this.rawName=e,this.description=t,this.config=r,this.cli=i,this.options=[],this.aliasNames=[],this.name=ac(e);let n=ac(e),s=n.indexOf(":");if(s>0)this.namespace=n.substring(0,s),this.name=n.substring(s+1);if(this.args=zw(e),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!r)this.config={}}usage(e){return this.usageText=e,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(e,t="-v, --version"){return this.versionNumber=e,this.option(t,"Display version number"),this}example(e){return this.examples.push(e),this}option(e,t,r){let i=new ch(e,t,r);return this.options.push(i),this}alias(e){return this.aliasNames.push(e),this}action(e){return this.commandAction=e,this}before(e){return this.beforeHooks.push(e),this}after(e){return this.afterHooks.push(e),this}use(e){return this.middleware.push(e),this}isMatched(e){if(this.aliasNames.includes(e))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===e;return this.name===e}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof uc}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(e){return e=e.split(".")[0],!!this.options.find((t)=>t.names.includes(e))}outputHelp(){let{name:e,commands:t}=this.cli,{versionNumber:r,options:i,helpCallback:n}=this.cli.globalCommand,s=[{body:`${e}${r?`/${r}`:""}`}];if(s.push({title:"Usage",body:` $ ${e} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&t.length>0){let a=th(t.map((d)=>d.rawName)),l=new Map,u=[];for(let d of t)if(d.namespace){if(!l.has(d.namespace))l.set(d.namespace,[]);l.get(d.namespace).push(d)}else u.push(d);let f="";if(u.length>0)f+=u.map((d)=>` ${oc(d.rawName,a.length)} ${d.description}`).join(`
|
|
302
|
+
`);let h=Array.from(l.keys()).sort();for(let d of h){let y=l.get(d);if(f.length>0)f+=`
|
|
302
303
|
|
|
303
|
-
`;f+=` ${
|
|
304
|
-
`,f+=
|
|
305
|
-
`)}
|
|
306
|
-
`)})}let
|
|
307
|
-
`)})}if(this.examples.length>0)
|
|
308
|
-
`)});if(
|
|
309
|
-
${
|
|
304
|
+
`;f+=` ${d}:
|
|
305
|
+
`,f+=y.map((g)=>` ${oc(g.rawName,a.length-2)} ${g.description}`).join(`
|
|
306
|
+
`)}s.push({title:"Commands",body:f}),s.push({title:"For more info, run any command with the `--help` flag",body:t.map((d)=>` $ ${e}${d.displayName===""?"":` ${d.displayName}`} --help`).join(`
|
|
307
|
+
`)})}let c=this.isGlobalCommand?i:[...this.options,...i||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)c=c.filter((a)=>a.name!=="version");if(c.length>0){let a=th(c.map((l)=>l.rawName));s.push({title:"Options",body:c.map((l)=>` ${oc(l.rawName,a.length)} ${l.description} ${l.config.default===void 0?"":`(default: ${l.config.default})`}`).join(`
|
|
308
|
+
`)})}if(this.examples.length>0)s.push({title:"Examples",body:this.examples.map((a)=>{if(typeof a==="function")return a(e);return a}).join(`
|
|
309
|
+
`)});if(n)s=n(s)||s;console.log(s.map((a)=>a.title?`${a.title}:
|
|
310
|
+
${a.body}`:a.body).join(`
|
|
310
311
|
|
|
311
|
-
`))}outputVersion(){let{name:
|
|
312
|
+
`))}outputVersion(){let{name:e}=this.cli,{versionNumber:t}=this.cli.globalCommand;if(t)console.log(`${e}/${t} ${typeof Bun<"u"?tv:rv}`)}checkRequiredArgs(){let e=this.args.filter((t)=>t.required).length;if(this.cli.args.length<e){let r=this.args.filter((n)=>n.required).slice(this.cli.args.length),i=r.map((n)=>`<${n.value}>`).join(" ");throw new Jn(`Missing required argument${r.length>1?"s":""}: ${i}
|
|
312
313
|
|
|
313
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:
|
|
314
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:e,globalCommand:t}=this.cli;if(!this.config.allowUnknownOptions){for(let r of Object.keys(e))if(r!=="--"&&!this.hasOption(r)&&!t.hasOption(r)){let n=[...t.options,...this.options].flatMap((a)=>a.names),s=r.length>1?`--${r}`:`-${r}`,o=ah(r,n),c=`Unknown option \`${s}\``;if(o.length>0)c+=`
|
|
314
315
|
|
|
315
|
-
Did you mean one of these?`,
|
|
316
|
-
• ${
|
|
316
|
+
Did you mean one of these?`,o.forEach((a)=>{let l=a.length>1?`--${a}`:`-${a}`;c+=`
|
|
317
|
+
• ${l}`});throw c+=`
|
|
317
318
|
|
|
318
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
319
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new Jn(c)}}}checkOptionValue(){let{options:e,globalCommand:t}=this.cli,r=[...t.options,...this.options];for(let i of r){let n=e[i.name.split(".")[0]];if(i.required){let s=r.some((o)=>o.negated&&o.names.includes(i.name));if(n===!0||n===!1&&!s)throw new Jn(`Option \`${i.rawName}\` requires a value.
|
|
319
320
|
|
|
320
|
-
Example: ${this.cli.name} ${this.rawName} ${
|
|
321
|
+
Example: ${this.cli.name} ${this.rawName} ${i.rawName} <value>`)}}}}class uc extends lc{constructor(e){super("@@global@@","",{},e)}}var iv=lc,ar={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var zi={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function nv(){return!0}function sv(){let e={};e.supportsColor=nv();function t(i,n=[]){let s=i===""?[]:[...n,i],o=function(a){if(!e.supportsColor)return a;let l="",u="";for(let f of s)if(f in zi&&zi[f]in ar){let h=zi[f];l+=ar[h][0],u=ar[h][1]+u}else if(f in ar)l+=ar[f][0],u=ar[f][1]+u;return l+a+u},c=[...Object.keys(ar),...Object.keys(zi)];for(let a of c)if(!(a in o))Object.defineProperty(o,a,{get(){return t(a,s)}});return o}let r=[...Object.keys(ar),...Object.keys(zi)];for(let i of r)if(!(i in e))Object.defineProperty(e,i,{get(){return t(i)}});return e}var Gi=sv();class fc extends Vw{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(e=""){super();this.name=e,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new uc(this),this.globalCommand.usage("<command> [options]")}handleSignals(e){if(this.signalHandlersSet)return this;let t=async(r)=>{if(console.log(`
|
|
321
322
|
|
|
322
|
-
Received ${
|
|
323
|
-
✗ Command "${
|
|
324
|
-
`)),this.enableDidYouMean){let
|
|
325
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
326
|
-
`),
|
|
327
|
-
`),A=$.split(`
|
|
328
|
-
`)
|
|
329
|
-
`)
|
|
330
|
-
`)}class KJ{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(w,$=!0){let{input:Y=vG,output:A=cG,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w(JQ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=mG.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),tY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xw.show),this.output.off("resize",this.render),tY(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(xw.show),this.output.off("resize",this.render),tY(this.input,!1),w(JQ)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&eY.aliases.has($.name))this.emit("cursor",eY.aliases.get($.name));if(eY.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(KQ([w,$?.name,$?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
331
|
-
`),tY(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let w=WQ(this._prevFrame,UQ.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
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
|
-
`);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
|
-
`).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 KJ{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 KJ{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:$,TM=$0("◆","*"),NM=$0("■","x"),qM=$0("▲","x"),HM=$0("◇","o"),RM=$0("┌","T"),sG=$0("│","|"),MM=$0("└","—"),IM=$0("●",">"),yM=$0("○"," "),CM=$0("◻","[•]"),VM=$0("◼","[+]"),LM=$0("◻","[ ]"),OM=$0("▪","•"),SM=$0("─","-"),_M=$0("╮","+"),hM=$0("├","+"),DM=$0("╯","+"),xM=$0("●","•"),kM=$0("◆","*"),ZM=$0("▲","!"),PM=$0("■","x");var iM={light:$0("─","-"),heavy:$0("━","="),block:$0("█","#")};function oG(){return`${oY.gray(sG)} `}var bM=oG();bA();QU();b8();D$();f0();import{spawn as hR}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)){K("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||d8.cwd();K("start",`Starting process ${w}:`,Y),K("start",` Command: ${A} ${X.join(" ")}`,Y),K("start",` Working directory: ${J}`,Y),K("start",` Environment variables: ${$$($.env)}`,Y);let U=hR(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)K("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)K("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)=>{K("process",`[${w}] ${Q.toString().trim()}`,!0)}),U.stderr?.on("data",(Q)=>{K("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 K("start",`Process ${w} started successfully`,Y),j()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){K("start",`No process found for ${w}`,$);return}return K("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),K("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){K("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){K("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){K("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,K("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;m$();D$();import{execSync as bR}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`,hw={bold:p8(1,22),dim:p8(2,22),green:p8(32,39),cyan:p8(36,39)};bA();b8();D$();m$();f0();import*as O6 from"node:fs";import*as S6 from"node:path";import*as Dw from"node:process";function DR(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??DR(B.to,B.path);if(!y$(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 u1({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??Xw(),Q=X.map((B)=>B.id),z=async()=>{if(j)return;j=!0;for(let B of Q)await c$(B,Y,$).catch((G)=>{K("runner",`removeEntry(${B}) failed: ${G}`,$)})},f=(B)=>{K("runner",`received ${B}, unregistering ${Q.length} entries`,$),z().finally(()=>Dw.exit(0))};Dw.once("SIGINT",f),Dw.once("SIGTERM",f),Dw.once("exit",()=>{if(j)return;for(let B of Q)try{O6.unlinkSync(S6.join(W,`${B}.json`))}catch{}}),await new Promise(()=>{})}Dj();Gj();Ij();import{timingSafeEqual as xR}from"node:crypto";function kR(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return xR(Y,A)}function r8(w){return w.toLowerCase().replace(/\.$/,"")}var ZR=["/.well-known/acme-challenge/"];function PR(w){let $=w.headers.get("host");if($)return r8($.split(":")[0]);try{return r8(new URL(w.url).hostname)}catch{return""}}function _6(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??ZR,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((z)=>h$(Q,z))},j=(W)=>{let Q=PR(W);if(!U(Q))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((f)=>z.startsWith(f)))return;if(kR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return j.protects=U,j}Ej();Tj();N8();y8();Hj();Rj();M8();f0();var h6={name:"@stacksjs/rpx",type:"module",version:"0.11.45",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 --production ./bin/cli.ts --compile --outfile bin/rpx",compile:"bun build --production ./bin/cli.ts --compile --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 --production ./bin/cli.ts --compile --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build --production ./bin/cli.ts --compile --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build --production ./bin/cli.ts --compile --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=h6.version;var a8=new n8,uR=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 K("cleanup","Cleanup already in progress, skipping",w?.verbose),pj||Promise.resolve();lj=!0,K("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),K("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{K("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){K("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),nY.clear();for(let A of o8)i1(A);if(o8.clear(),w?.hosts&&w.domains?.length){K("cleanup","Cleaning up hosts file entries",w?.verbose),K("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(K("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(()=>{K("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{K("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){K("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await K2(X,w?.verbose),K("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){K("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($),K("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){K("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){K("signal",`Received second ${w} signal, forcing exit`,!0),d.exit(1);return}rj=!0,K("signal",`Received ${w} signal, initiating cleanup`,!0),$J().catch(($)=>{K("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){K("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(d.env.RPX_BYPASS_CONNECTION_TEST==="true"){K("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",()=>{K("connection",`Successfully connected to ${w}:${$}`,Y),Q.end(),j()}),Q.once("timeout",()=>{K("connection",`Connection to ${w}:${$} timed out`,Y),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(z)=>{K("connection",`Failed to connect to ${w}:${$}: ${z}`,Y),Q.destroy(),W(z)})});try{await U()}catch(j){let W=j;if(Date.now()-J>X){K("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 K("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),lY(w,$,Y,A-1);if(A>0)try{K("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((z,f)=>{let B=e8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{K("connection",`Received HTTP response with status: ${G.statusCode}`,Y),z()});B.on("error",(G)=>f(G)),B.on("timeout",()=>{B.destroy(),f(Error("HTTP request timed out"))}),B.end()}),K("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(z){return K("connection",`HTTP request to ${w}:${$} failed: ${z}`,Y),K("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((f)=>setTimeout(f,2000)),lY(w,$,Y,A-1)}let Q=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;K("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){K("server",`Starting server with options: ${$$(w)}`,w.verbose);let $=b$(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")){K("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 K("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){K("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(K("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 K("server",`SSL setup failed: ${j}`,w.verbose),j}K("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await cR({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function vR(w,$,Y,A,X,J,U,j,W,Q,z,f){K("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${j}`,U);let B=RY(z??A.host,f);IY(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 i1(B),Error(`Failed to start proxy server for ${$} on port ${Y}`);o8.add(B),gR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:j,verbose:U})}async function cR(w){K("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:z}=w,f=80,B=443,G=v6(),T=w.portManager||uR,F=tj(w);try{if(F&&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(F&&d.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await bY([A],U))[0]){K("hosts",`${A} not found in hosts file, adding...`,U);try{await iY([A],U)}catch(L){K("hosts",`Failed to add ${A} to hosts file: ${L}`,U)}}}if(J&&!T.usedPorts.has(f)){if(!await I$(f,G,U))K("setup","Starting HTTP redirect server",U),i6(U),T.usedPorts.add(f);else if(K("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 E=J?B:f,N=await I$(E,G,U),R;if(N){if(K("setup",`Port ${E} is already in use`,U),U)H.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(R=await T.getNextAvailablePort(3443,!0),K("setup",`Using port ${R} instead of ${E}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(E+1000,!0),K("setup",`Using port ${R} instead of ${E}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=E,T.usedPorts.add(R),K("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await vR($,A,R,X,J,W,U,z,Q,CY(w.auth),Y,w.loadBalancer)}catch(E){K("setup",`Setup failed: ${E}`,U),H.error(`Failed to setup reverse proxy: ${E.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,J){K("redirect",`Starting HTTP redirect server on port ${$}`,w);let U=e8.createServer((j,W)=>{let Q=j.url?j.url.split("?",1)[0]:"";if(Q.startsWith("/.well-known/acme-challenge/")){if(X){let G=X.challengeStore.handlePath(Q);if(G!==void 0){K("redirect",`Serving on-demand ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(A){let G=I8(A,Q);if(G!=null){K("redirect",`Serving ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(X){W.writeHead(404,{"content-type":"text/plain"}),W.end("challenge not found");return}}let z=j.headers.host||"",f=z.includes(":")?z.slice(0,z.indexOf(":")):z;if(X&&f&&!X.hasCert(f)&&(!J||J(f)))X.ensureCert(f).catch(()=>{});let B=Y===443?f:`${f}:${Y}`;K("redirect",`Redirecting request from ${z}${j.url} to https://${B}`,w),W.writeHead(301,{Location:`https://${B}${j.url}`}),W.end()}).listen($);nY.add(U),K("redirect","HTTP redirect server started",w)}function b6(w){let $={...vw,...w};if(K("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 K("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((W)=>{K("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};K("proxy",`Server options: ${$$(j)}`,$.verbose),P6(j).catch((W)=>{K("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 mR(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=mR($),A=tj($);if(K("config",`Starting with config: ${$$($,2)}`,Y),K("config",`Is multi-proxy? ${"proxies"in $}`,Y),K("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)){K("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let q of $.proxies)if(q.start){let C=`${q.from}-${q.to}`;try{K("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=b$(q.from),D=new URL(M.startsWith("http")?M:`http://${M}`),n=D.hostname||"localhost",a0=Number(D.port)||80;try{await lY(n,a0,Y),K("watch",`Dev server is ready at ${n}:${a0}`,Y)}catch(Uw){K("watch",`Connection check failed, but continuing with proxy setup: ${Uw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw K("watch",`Failed to start command for ${C}: ${M}`,Y),Error(`Failed to start command for ${C}: ${M}`)}}else K("watch",`No start command for proxy ${q.from} -> ${q.to}`,Y)}else if("start"in $&&$.start){K("watch","Found start command in single proxy config",Y);let q=`${$.from}-${$.to}`;try{if($.start)K("watch",`Starting command: ${$.start.command}`,Y),await a8.startProcess(q,$.start,Y);let C=b$($.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),K("watch",`Dev server is ready at ${D}:${n}`,Y)}catch(a0){K("watch",`Connection check failed, but continuing with proxy setup: ${a0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw K("watch",`Failed to run start command: ${C}`,Y),Error(`Failed to run start command: ${C}`)}}else K("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(!E$())try{K("sudo","Pre-acquiring sudo credentials for privileged operations",Y),bR("sudo -v",{stdio:"inherit"})}catch{K("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await DY($.productionCerts,Y),J.length>0)K("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(K("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 K("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")),z=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"],B=[...new Set(Q.map((q)=>q.split(".").pop()?.toLowerCase()))],G=B.filter((q)=>!!q&&z.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&&f.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 K("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{K("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),i8));await q({verbose:$.verbose})}catch(q){K("cleanup",`Error stopping DNS server: ${q}`,$.verbose)}try{await a8.stopAll($.verbose)}catch(q){K("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 F=$.singlePortMode===!0,E=$.httpsPort??443,N=$.httpPort??80,R=$.originGuard?_6($.originGuard):null,V=!!W&&(U.length>1||F||J.length>0),L=!W&&F&&U.length>0;if(V&&W){K("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let q=await D6(U,A,Y),C=null,M=$.onDemandTls,D=M?.enabled?new b1({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??k6.join(wJ.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(i0)=>{if(xY()==="restart")K("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>d.kill(d.pid,"SIGTERM"),10).unref();else Uw(i0)}}):null,n=null,a0=!1;async function Uw(i0){if(n=i0,a0)return;a0=!0;try{while(n){let Ww=n;if(n=null,K("proxies",`rebuilding :${E} with ${Ww.length} SNI cert(s)`,Y),C)nY.delete(C),C.stop(!1);let v0=!1;for(let _=0;!v0&&_<60;_++){let c0=s8({routeEntries:q,listenPort:E,sslConfig:Ww,originGuard:R,verbose:Y});if(c0){C=c0,v0=!0;break}await new Promise((n1)=>setTimeout(n1,Math.min(25*2**Math.min(_,4),500)))}if(!v0)H.error(`rpx: CRITICAL — could not rebind :${E} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{a0=!1}}if(!await I$(N,"0.0.0.0",Y)){let i0=new Set(q.map((v0)=>v0.host)),Ww=(v0)=>i0.has(v0)||[...i0].some((_)=>h$(v0,_));i6(Y,N,E,$.acmeChallengeWebroot,D,Ww)}if(await I$(E,"0.0.0.0",Y)){if(K("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${E} 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:E,sslConfig:J$,originGuard:R,verbose:Y}),!C){H.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(L){K("proxies",`Creating shared HTTP server for ${U.length} domains on port ${N}`,Y);let q=await D6(U,A,Y);if(await I$(N,"0.0.0.0",Y)){if(K("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";K("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){K("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),z=CY(J.auth);if(J.redirect){let f=_2(J.redirect);A.push({host:U,path:W,route:{redirect:f,basePath:Q,auth:z}}),K("proxies",`Route: ${U}${W??""} → redirect ${f.status} ${f.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:R8(J.static,j),cleanUrls:j,basePath:Q,auth:z}}),K("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let f=b$(J.from),B=new URL(f.startsWith("http")?f:`http://${f}`),G=RY(J.from??B.host,J.loadBalancer);IY(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:z}}),K("proxies",`Route: ${U}${W??""} → ${B.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!W1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await bY([U],Y))[0])await iY([U],Y)}catch{K("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}var dY=null;function v6(){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=SY($),j=LY((z,f)=>_Y(U,z,f),J),W=X?(z,f)=>X(z)??j(z,f):j,Q=OY(J);try{let z=Bun.serve({port:Y,hostname:v6(),reusePort:TY(),...A?{tls:v$(Array.isArray(A)?A.map((f)=>({serverName:f.serverName,key:f.key,cert:f.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(f,B){return W(f,B)},websocket:Q,error(f){return K("server",`Shared proxy server error: ${f}`,J),new Response(`Server Error: ${f.message}`,{status:500})}});return nY.add(z),K("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return K("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function gR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${hw.green(hw.bold("rpx"))} ${hw.green(`v${gY}`)}`),console.log(` ${hw.green("➜")} ${hw.dim(w?.from??"")} ${hw.dim("➜")} ${hw.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${hw.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${hw.green("➜")} Clean URLs enabled`)}f0();P0.chdir(nR(dR(lR(import.meta.url)),".."));var u0=new GJ("rpx");u0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return u6(vw);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($)});u0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=G8(vw)?vw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):vw.to===w?vw: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)}});u0.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)}});u0.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 c6(w){let Y={...(await vz().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}u0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await c6(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)}});u0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(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)":""}`)});u0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(w)=>{let $=w.rpxDir??V0(),Y=await V$($),A=await m8($),X=w.registryDir,J=await Tw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:L$($),rpxDir:$,registryDir:X??Xw(),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??Xw()}`),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})`)}});u0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!y$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await u1({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)}});u0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(w,$)=>{if(!y$(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})`)});u0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(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")});u0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await c6(w.roots),Y=lz($),A=await Tw(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}`)});u0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("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
|
-
`);P0.stdout.write((j&&j>0?W.slice(-j):W).join(`
|
|
338
|
-
`))});u0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(gY)});u0.version(gY);u0.help();u0.run();
|
|
323
|
+
Received ${r}, cleaning up...`),e)try{await e()}catch(i){console.error("Error during cleanup:",i)}or.exit(0)};return or.on("SIGINT",()=>t("SIGINT")),or.on("SIGTERM",()=>t("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(e=!0){return this.enableDidYouMean=e,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(e){return this.globalCommand.usage(e),this}command(e,t,r){if(!r)r={};let i=new iv(e,t||"",r,this);return i.globalCommand=this.globalCommand,this.commands.push(i),i}option(e,t,r){return this.globalCommand.option(e,t,r),this}help(e){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=e,this.showHelpOnExit=!0,this}version(e,t="-v, --version"){return this.globalCommand.version(e,t),this.showVersionOnExit=!0,this}example(e){return this.globalCommand.example(e),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:e,options:t},r,i){if(this.args=e,this.options=t,r)this.matchedCommand=r;if(i)this.matchedCommandName=i;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(e){if(console.log(Gi.red(`
|
|
324
|
+
✗ Command "${e}" not found.
|
|
325
|
+
`)),this.enableDidYouMean){let t=[];for(let i of this.commands){if(i.displayName)t.push(i.displayName);if(i.aliasNames)t.push(...i.aliasNames)}let r=ah(e,t);if(r.length>0)console.log(Gi.yellow("Did you mean one of these?")),r.forEach((i)=>console.log(` ${Gi.dim("•")} ${this.name} ${i}`)),console.log("")}console.log(Gi.dim("Run"),`${this.name} --help`,Gi.dim("to see all available commands")),or.exit(1)}async parse(e=ih,t={}){let{run:r=!0,exitOnError:i=!1}=t;if(i)try{return await this.parse(e,{run:r})}catch(a){throw this.handleUsageError(a),a}if(this.rawArgs=e,!this.name)this.name=e[1]?Qw(e[1]):"cli";let n=!0,s=e.slice(2),o=s[0];if(o&&!o.startsWith("-")){for(let a of this.commands)if(a.isMatched(o)){let l=this.mri(s,a);n=!1;let u={...l,args:l.args.slice(1)};this.setParsedInfo(u,a,o),this.emit(`command:${o}`,a);break}}if(n){for(let a of this.commands)if(a.name===""){n=!1;let l=this.mri(s,a);this.setParsedInfo(l,a),this.emit("command:!",a);break}}if(n){let a=this.mri(e.slice(2));this.setParsedInfo(a)}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(),r=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),r=!1,this.unsetMatchedCommand();let c={args:this.args,options:this.options};if(r)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return c}mri(e,t){let r=[...this.globalCommand.options,...t?t.options:[]],i=Gw(r),n=[],s=e.indexOf("--");if(s>-1)n=e.slice(s+1),e=e.slice(0,s);let o=Yw(e,i),c={_:o._};for(let h of Object.keys(o))if(h!=="_")c[oh(h)]=o[h];let a=c._,l={"--":n},u=t&&t.config.ignoreOptionDefaultValue?t.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,f=Object.create(null);for(let h of r){if(!u&&h.config.default!==void 0)for(let d of h.names)l[d]=h.config.default;if(Array.isArray(h.config.type)){if(f[h.name]===void 0)f[h.name]={shouldTransform:!0,transformFunction:h.config.type[0]}}}for(let h of Object.keys(c))if(h!=="_"){let d=h.split(".");Jw(l,d,c[h]),Xw(l,f)}return{args:a,options:l}}async run(e=ih){return this.parse(e,{run:!0,exitOnError:!0})}handleUsageError(e){if(!(!!e&&typeof e==="object"&&e.name==="ClappError"&&e.isUsageError!==!1))return;let i=e,n=i.message??"command-line error",s=this.name?`${this.name}: `:"",o=/--help/.test(n)?"":`
|
|
326
|
+
Run \`${this.name??"cli"} --help\` for usage.`;or.stderr.write(`${s}${n}${o}
|
|
327
|
+
`),or.exit(i.exitCode??2)}async runMatchedCommand(){let{args:e,options:t,matchedCommand:r}=this;if(!r||!r.commandAction)return;r.checkUnknownOptions(),r.checkOptionValue(),r.checkRequiredArgs();let i=[];r.args.forEach((c,a)=>{if(c.variadic)i.push(e.slice(a));else i.push(e[a])}),i.push(t);let n={command:r,args:i,options:t};for(let c of r.beforeHooks)await c(n);let s,o=async()=>{let c=r.commandAction.apply(this,i);if(c instanceof Promise)s=await c;else s=c;return s};if(r.middleware.length>0){let c=0,a=async()=>{if(c<r.middleware.length){let l=r.middleware[c++];await l({...n,next:a})}else await o()};await a()}else await o();for(let c of r.afterHooks)await c(n);return s}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return or.removeAllListeners("SIGINT"),or.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 lh{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(e){if(!this.enabled){this.misses++;return}let t=this.cache.get(e);if(!t){this.misses++;return}if(Date.now()-t.timestamp>t.ttl){this.cache.delete(e),this.misses++;return}return this.hits++,t.value}set(e,t,r=5000){if(!this.enabled)return;this.cache.set(e,{value:t,timestamp:Date.now(),ttl:r})}has(e){if(!this.enabled)return!1;let t=this.cache.get(e);if(!t)return!1;if(Date.now()-t.timestamp>t.ttl)return this.cache.delete(e),!1;return!0}delete(e){this.cache.delete(e)}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 e=Date.now();for(let[t,r]of this.cache.entries())if(e-r.timestamp>r.ttl)this.cache.delete(t)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var qR=new lh;function ov(){if("FORCE_COLOR"in qi.env)return qi.env.FORCE_COLOR!=="0";if("NO_COLOR"in qi.env||qi.env.TERM==="dumb")return!1;if(qi.platform==="win32")return!0;return nh.isatty(1)&&nh.isatty(2)}var uh=ov();function oe(e,t){if(!uh)return(r)=>r;return(r)=>e+r+t}var av=oe("\x1B[0m","\x1B[0m"),cv=oe("\x1B[31m","\x1B[39m"),lv=oe("\x1B[32m","\x1B[39m"),uv=oe("\x1B[33m","\x1B[39m"),fv=oe("\x1B[34m","\x1B[39m"),hv=oe("\x1B[35m","\x1B[39m"),dv=oe("\x1B[36m","\x1B[39m"),mv=oe("\x1B[37m","\x1B[39m"),gv=oe("\x1B[90m","\x1B[39m"),pv=oe("\x1B[1m","\x1B[22m"),yv=oe("\x1B[3m","\x1B[23m"),wv=oe("\x1B[4m","\x1B[24m"),vv=oe("\x1B[2m","\x1B[22m"),bv=oe("\x1B[7m","\x1B[27m"),$v=oe("\x1B[8m","\x1B[28m"),xv=oe("\x1B[9m","\x1B[29m"),Cv=oe("\x1B[41m","\x1B[49m"),Sv=oe("\x1B[42m","\x1B[49m"),Ev=oe("\x1B[43m","\x1B[49m"),Tv=oe("\x1B[44m","\x1B[49m"),Pv=oe("\x1B[45m","\x1B[49m"),Rv=oe("\x1B[46m","\x1B[49m"),Av=oe("\x1B[47m","\x1B[49m"),kv=uh,Ov={reset:av,red:cv,green:lv,yellow:uv,blue:fv,magenta:hv,cyan:dv,white:mv,gray:gv,bold:pv,italic:yv,underline:wv,dim:vv,inverse:bv,hidden:$v,strikethrough:xv,bgRed:Cv,bgGreen:Sv,bgYellow:Ev,bgBlue:Tv,bgMagenta:Pv,bgCyan:Rv,bgWhite:Av,isColorSupported:kv},Nv=Ov,Fv=["up","down","left","right","space","enter","cancel"],tA={actions:new Set(Fv),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};var rA=Dv.platform.startsWith("win"),iA=Symbol("clapp:cancel");var Bv=Zw();var re=(e,t)=>Bv?e:t,nA=re("◆","*"),sA=re("■","x"),oA=re("▲","x"),aA=re("◇","o"),cA=re("┌","T"),Lv=re("│","|"),lA=re("└","—"),uA=re("●",">"),fA=re("○"," "),hA=re("◻","[•]"),dA=re("◼","[+]"),mA=re("◻","[ ]"),gA=re("▪","•"),pA=re("─","-"),yA=re("╮","+"),wA=re("├","+"),vA=re("╯","+"),bA=re("●","•"),$A=re("◆","*"),xA=re("▲","!"),CA=re("■","x");var SA={light:re("─","-"),heavy:re("━","="),block:re("█","#")};function Mv(){return`${Nv.gray(Lv)} `}var EA=Mv();Ls();ol();Ma();Nr();he();import{spawn as yR}from"node:child_process";import*as Ka from"node:process";class Ha{processes=new Map;isShuttingDown=!1;async startProcess(e,t,r){if(this.processes.has(e)){m("start",`Process ${e} is already running`,r);return}let[i,...n]=t.command.split(" "),s=t.cwd||Ka.cwd();m("start",`Starting process ${e}:`,r),m("start",` Command: ${i} ${n.join(" ")}`,r),m("start",` Working directory: ${s}`,r),m("start",` Environment variables: ${tr(t.env)}`,r);let o=yR(i,n,{cwd:s,env:{...Ka.env,...t.env},shell:!0,stdio:"inherit"});return this.processes.set(e,{command:t.command,cwd:s,process:o,env:t.env}),new Promise((c,a)=>{if(o.on("error",(l)=>{if(!this.isShuttingDown)m("start",`Process ${e} failed to start: ${l}`,r),this.processes.delete(e),a(l)}),o.on("exit",(l)=>{if(!this.isShuttingDown&&l!==null&&l!==0)m("start",`Process ${e} exited with code ${l}; leaving the proxy running`,r),this.processes.delete(e),a(Error(`Process ${e} exited with code ${l}`))}),r)o.stdout?.on("data",(l)=>{m("process",`[${e}] ${l.toString().trim()}`,!0)}),o.stderr?.on("data",(l)=>{m("process",`[${e}] ERR: ${l.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&o.killed)this.processes.delete(e),a(Error(`Process ${e} was killed during startup`));else m("start",`Process ${e} started successfully`,r),c()},1000)})}async stopProcess(e,t){let r=this.processes.get(e);if(!r?.process){m("start",`No process found for ${e}`,t);return}return m("start",`Stopping process ${e}`,t),new Promise((i)=>{if(!r.process){i();return}r.process.once("exit",()=>{this.processes.delete(e),m("start",`Process ${e} stopped`,t),i()});try{r.process.kill("SIGTERM"),setTimeout(()=>{if(r.process){m("start",`Force killing process ${e}`,t);try{r.process.kill("SIGKILL")}catch(n){}}},3000)}catch(n){m("start",`Error stopping process ${e}: ${n}`,t),this.processes.delete(e),i()}})}async stopAll(e){if(this.isShuttingDown){m("start","Already shutting down, skipping duplicate stopAll call",e);return}this.isShuttingDown=!0,m("start","Stopping all processes",e);let t=Array.from(this.processes.keys()).map((r)=>this.stopProcess(r,e).catch((i)=>{x.error(`Failed to stop process ${r}:`,i)}));await Promise.allSettled(t),this.processes.clear(),this.isShuttingDown=!1}isRunning(e){let t=this.processes.get(e);return!!t?.process&&!t.process.killed}}var Va=new Ha;Wr();Nr();import{execSync as SR}from"node:child_process";import*as Qa from"node:http";import*as Rw from"node:net";import*as Za from"node:os";import*as Aw from"node:path";import*as Y from"node:process";var Ya=(e,t)=>(r)=>`\x1B[${e}m${r}\x1B[${t}m`,Nt={bold:Ya(1,22),dim:Ya(2,22),green:Ya(32,39),cyan:Ya(36,39)};Ls();Ma();Nr();Wr();he();import*as Cw from"node:fs";import*as Sw from"node:path";import*as Dt from"node:process";function wR(e,t){let i=(t&&t!=="/"?`${e}${t}`:e).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return i.length>0?i:"rpx"}async function Hf(e){if(e.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let t=e.verbose??!1,r=e.registryDir,i=new Set,n=e.proxies.map((h)=>{let d=h.id??wR(h.to,h.path);if(!Sr(d))throw Error(`invalid registry id "${d}" derived from to="${h.to}"`);if(i.has(d))throw Error(`duplicate registry id "${d}" — set an explicit \`id\` on one of the proxies`);return i.add(d),{...h,id:d}}),s=new Date().toISOString();for(let h of n)await _i({id:h.id,from:h.from,to:h.to,path:h.path,pid:e.persistent?void 0:Dt.pid,cwd:Dt.cwd(),createdAt:s,cleanUrls:h.cleanUrls,changeOrigin:h.changeOrigin,pathRewrites:h.pathRewrites,static:h.static,loadBalancer:h.loadBalancer},r,t);let o=await Wa({rpxDir:e.rpxDir,verbose:t,spawnCommand:e.spawnCommand,startupTimeoutMs:e.startupTimeoutMs,spawnEnv:e.spawnEnv});for(let h of n){let d=h.static?`static ${typeof h.static==="string"?h.static:h.static.dir}`:h.from;x.success(`https://${h.to} → ${d}`)}if(x.info(`(via rpx daemon pid=${o.pid}; \`rpx daemon:status\` to inspect)`),e.detached)return;let c=!1,a=r??st(),l=n.map((h)=>h.id),u=async()=>{if(c)return;c=!0;for(let h of l)await Ur(h,r,t).catch((d)=>{m("runner",`removeEntry(${h}) failed: ${d}`,t)})},f=(h)=>{m("runner",`received ${h}, unregistering ${l.length} entries`,t),u().finally(()=>Dt.exit(0))};Dt.once("SIGINT",f),Dt.once("SIGTERM",f),Dt.once("exit",()=>{if(c)return;for(let h of l)try{Cw.unlinkSync(Sw.join(a,`${h}.json`))}catch{}}),await new Promise(()=>{})}Of();ff();xf();import{timingSafeEqual as vR}from"node:crypto";function bR(e,t){if(e==null)return!1;let r=Buffer.from(e),i=Buffer.from(t);if(r.length!==i.length)return!1;return vR(r,i)}function za(e){return e.toLowerCase().replace(/\.$/,"")}var $R=["/.well-known/acme-challenge/"];function xR(e){let t=e.headers.get("host");if(t)return za(t.split(":")[0]);try{return za(new URL(e.url).hostname)}catch{return""}}function Ew(e){let t=e.header.toLowerCase(),r=new Set,i=[];for(let a of e.hosts){let l=za(a);if(l.startsWith("*."))i.push(l);else r.add(l)}let n=e.exemptPaths??$R,s=e.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
328
|
+
`,o=(a)=>{let l=za(a);return r.has(l)||i.some((u)=>Or(l,u))},c=(a)=>{let l=xR(a);if(!o(l))return;let u="/";try{u=new URL(a.url).pathname}catch{}if(n.some((f)=>u.startsWith(f)))return;if(bR(a.headers.get(t),e.value))return;return new Response(s,{status:403,headers:{"content-type":"text/plain"}})};return c.protects=o,c}gf();pf();ya();Ca();vf();bf();$a();he();var Tw={name:"@stacksjs/rpx",type:"module",version:"0.11.46",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 --production ./bin/cli.ts --compile --outfile bin/rpx",compile:"bun build --production ./bin/cli.ts --compile --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 --production ./bin/cli.ts --compile --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build --production ./bin/cli.ts --compile --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build --production ./bin/cli.ts --compile --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build --production ./bin/cli.ts --compile --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build --production ./bin/cli.ts --compile --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 Hn=Tw.version;var qa=new Ha,ER=new Ta("0.0.0.0"),Yn=new Set,Xa=new Set,Vf=!1,Ga=null,Yf=null;async function ec(e){if(Vf)return m("cleanup","Cleanup already in progress, skipping",e?.verbose),Yf||Promise.resolve();Vf=!0,m("cleanup","Starting cleanup process",e?.verbose),Yf=new Promise((t)=>{Ga=t});try{await qa.stopAll(e?.verbose),x.info("Shutting down proxy servers...");let t=[],r=Array.from(Yn).map((i)=>new Promise((n)=>{let s=i;try{if(typeof s.stop==="function")s.stop(!0),m("cleanup","Bun server stopped",e?.verbose),n();else if(typeof s.close==="function")s.close(()=>{m("cleanup","Server closed successfully",e?.verbose),n()});else n()}catch(o){m("cleanup",`Error stopping server: ${o}`,e?.verbose),n()}}));t.push(...r),Yn.clear();for(let i of Xa)Mi(i);if(Xa.clear(),e?.hosts&&e.domains?.length){m("cleanup","Cleaning up hosts file entries",e?.verbose),m("cleanup",`Original domains for cleanup: ${JSON.stringify(e.domains)}`,e?.verbose);let i=e.domains.filter((n)=>{if(n==="test.local")return!0;return n!=="localhost"&&!n.startsWith("localhost.")&&n!=="127.0.0.1"});if(m("cleanup",`Filtered domains for cleanup: ${JSON.stringify(i)}`,e?.verbose),i.length>0)x.info("Cleaning up hosts file entries..."),t.push(qy(i,e?.verbose).then(()=>{m("cleanup",`Removed hosts entries for ${i.join(", ")}`,e?.verbose)}).catch((n)=>{m("cleanup",`Failed to remove hosts entries: ${n}`,e?.verbose),x.warn(`Failed to clean up hosts file entries for ${i.join(", ")}:`,n)}))}if(e?.certs&&e.domains?.length){m("cleanup","Cleaning up SSL certificates",e?.verbose),x.info("Cleaning up SSL certificates...");let i=e.domains.map(async(n)=>{try{await ly(n,e?.verbose),m("cleanup",`Removed certificates for ${n}`,e?.verbose)}catch(s){m("cleanup",`Failed to remove certificates for ${n}: ${s}`,e?.verbose),x.warn(`Failed to clean up certificates for ${n}:`,s)}});t.push(...i)}await Promise.allSettled(t),m("cleanup","All cleanup tasks completed successfully",e?.verbose),x.success("All cleanup tasks completed successfully")}catch(t){m("cleanup",`Error during cleanup: ${t}`,e?.verbose),x.error("Error during cleanup:",t)}finally{if(Ga)Ga();Ga=null,Vf=!1;let t=e&&"vitePluginUsage"in e&&e.vitePluginUsage===!0;if(Y.env.NODE_ENV!=="test"&&Y.env.BUN_ENV!=="test"&&!t)Y.exit(0)}return Yf}var zf=!1;function kw(e){if(zf){m("signal",`Received second ${e} signal, forcing exit`,!0),Y.exit(1);return}zf=!0,m("signal",`Received ${e} signal, initiating cleanup`,!0),ec().catch((t)=>{m("signal",`Cleanup failed after ${e}: ${t}`,!0),Y.exit(1)}).finally(()=>{zf=!1})}Y.once("SIGINT",()=>kw("SIGINT"));Y.once("SIGTERM",()=>kw("SIGTERM"));Y.on("uncaughtException",(e)=>{x.error("Uncaught exception (continuing):",e)});Y.on("unhandledRejection",(e)=>{x.error("Unhandled rejection (continuing):",e)});async function zn(e,t,r,i=5){m("connection",`Testing connection to ${e}:${t} (retries left: ${i})`,r);let n=15000,s=Date.now();if(Y.env.RPX_BYPASS_CONNECTION_TEST==="true"){m("connection",`Bypassing connection test for ${e}:${t} due to RPX_BYPASS_CONNECTION_TEST flag`,r);return}let o=()=>new Promise((c,a)=>{let l=Rw.connect({host:e,port:t,timeout:3000});l.once("connect",()=>{m("connection",`Successfully connected to ${e}:${t}`,r),l.end(),c()}),l.once("timeout",()=>{m("connection",`Connection to ${e}:${t} timed out`,r),l.destroy(),a(Error("Connection timed out"))}),l.once("error",(u)=>{m("connection",`Failed to connect to ${e}:${t}: ${u}`,r),l.destroy(),a(u)})});try{await o()}catch(c){let a=c;if(Date.now()-s>n){m("connection",`Connection test timed out after ${n}ms, but continuing anyway`,r),x.warn(`Connection test to ${e}:${t} timed out, but RPX will try to proceed anyway.`);return}if(a.code==="ECONNREFUSED"&&i>0)return m("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${i} retries left)`,r),await new Promise((u)=>setTimeout(u,2000)),zn(e,t,r,i-1);if(i>0)try{m("connection",`Trying HTTP request to ${e}:${t}`,r),await new Promise((u,f)=>{let h=Qa.request({hostname:e,port:t,path:"/",method:"HEAD",timeout:5000},(d)=>{m("connection",`Received HTTP response with status: ${d.statusCode}`,r),u()});h.on("error",(d)=>f(d)),h.on("timeout",()=>{h.destroy(),f(Error("HTTP request timed out"))}),h.end()}),m("connection",`HTTP request to ${e}:${t} succeeded`,r);return}catch(u){return m("connection",`HTTP request to ${e}:${t} failed: ${u}`,r),m("connection",`Retrying socket connection in 2 seconds... (${i} retries left)`,r),await new Promise((f)=>setTimeout(f,2000)),zn(e,t,r,i-1)}let l=`Failed to connect to ${e}:${t} after ${5-i} attempts: ${a.message}`;m("connection",`${l}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,r),x.warn(l),x.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 Ow(e){m("server",`Starting server with options: ${tr(e)}`,e.verbose);let t=Ir(e.from),r=new URL(t.startsWith("http")?t:`http://${t}`),i=new URL((e.to?.startsWith("http")?e.to:`http://${e.to}`)||"rpx.localhost"),n=Number.parseInt(r.port)||(r.protocol.includes("https:")?443:80),s=[i.hostname];if(Gf(e)&&!i.hostname.includes("localhost")&&!i.hostname.includes("127.0.0.1")){m("hosts",`Checking if hosts file entry exists for: ${i.hostname}`,e?.verbose);try{if(!(await _n(s,e.verbose))[0]){x.info(`Adding ${i.hostname} to hosts file...`),x.info("This may require sudo/administrator privileges");try{await In(s,e.verbose)}catch(a){if(x.error("Failed to add hosts entry:",a.message),x.warn("You can manually add this entry to your hosts file:"),x.warn(`127.0.0.1 ${i.hostname}`),x.warn(`::1 ${i.hostname}`),Y.platform==="win32")x.warn("On Windows:"),x.warn("1. Run notepad as administrator"),x.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else x.warn("On Unix systems:"),x.warn("sudo nano /etc/hosts")}}else m("hosts",`Host entry already exists for ${i.hostname}`,e.verbose)}catch(c){x.error("Failed to check hosts file:",c.message)}}try{await zn(r.hostname,n,e.verbose)}catch(c){m("server",`Connection test failed: ${c}`,e.verbose),x.error(c.message),x.warn("Continuing with proxy setup despite connection test failure..."),x.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let o=e._cachedSSLConfig||null;if(e.https)try{if(e.https===!0)e.https=$n({...e,to:i.hostname});if(o=await xr({...e,to:i.hostname,https:e.https}),!o){if(m("ssl",`Generating new certificates for ${i.hostname}`,e.verbose),await bn({...e,from:r.toString(),to:i.hostname,https:e.https}),o=await xr({...e,to:i.hostname,https:e.https}),!o)throw Error(`Failed to load SSL configuration after generating certificates for ${i.hostname}`)}}catch(c){throw m("server",`SSL setup failed: ${c}`,e.verbose),c}m("server",`Setting up reverse proxy with SSL config for ${i.hostname}`,e.verbose),await PR({...e,from:t,originalFrom:e.from||t,to:i.hostname,fromPort:n,sourceUrl:{hostname:r.hostname,host:r.host},ssl:o})}async function TR(e,t,r,i,n,s,o,c,a,l,u,f){m("proxy",`Creating proxy server ${e} -> ${t} with cleanUrls: ${c}`,o);let h=xn(u??i.host,f);Sn(h);let d=[{host:t,route:{sourceHost:i.host,upstreamPool:h,cleanUrls:c||!1,changeOrigin:a||!1,basePath:"/",auth:l}}];if(!Ja({routeEntries:d,listenPort:r,sslConfig:n,originGuard:null,verbose:o??!1}))throw Mi(h),Error(`Failed to start proxy server for ${t} on port ${r}`);Xa.add(h),AR({from:e,to:t,vitePluginUsage:s,listenPort:r,ssl:!!n,cleanUrls:c,verbose:o})}async function PR(e){m("setup",`Setting up reverse proxy: ${tr(e)}`,e.verbose);let{from:t,originalFrom:r,to:i,sourceUrl:n,ssl:s,verbose:o,cleanup:c,vitePluginUsage:a,changeOrigin:l,cleanUrls:u}=e,f=80,h=443,d=Bw(),y=e.portManager||ER,g=Gf(e);try{if(g&&i&&!i.includes("localhost")&&!i.includes("127.0.0.1")){if(!(await _n([i],o))[0]){x.warn(`The hostname ${i} isn't in your hosts file. Adding it now...`);try{await In([i],o),x.success(`Added ${i} to your hosts file.`)}catch(R){x.error(`Failed to add ${i} to your hosts file: ${R}`),x.info(`You may need to manually add '127.0.0.1 ${i}' to your /etc/hosts file.`)}}}else if(g&&Y.platform!=="darwin"&&i&&i.includes("localhost")&&!i.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await _n([i],o))[0]){m("hosts",`${i} not found in hosts file, adding...`,o);try{await In([i],o)}catch(R){m("hosts",`Failed to add ${i} to hosts file: ${R}`,o)}}}if(s&&!y.usedPorts.has(f)){if(!await Cr(f,d,o))m("setup","Starting HTTP redirect server",o),Nw(o),y.usedPorts.add(f);else if(m("setup","Port 80 is in use, skipping HTTP redirect",o),o)x.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let p=s?h:f,w=await Cr(p,d,o),b;if(w){if(m("setup",`Port ${p} is already in use`,o),o)x.warn(`Port ${p} is already in use. This may be another instance of rpx or another service.`);if(p===443){if(b=await y.getNextAvailablePort(3443,!0),m("setup",`Using port ${b} instead of ${p}`,o),o)x.info(`Using port ${b} instead. Access your site at https://${i}:${b}`)}else if(b=await y.getNextAvailablePort(p+1000,!0),m("setup",`Using port ${b} instead of ${p}`,o),o)x.info(`Using port ${b} instead. Access your site at http://${i}:${b}`)}else b=p,y.usedPorts.add(b),m("setup",`Using standard ${p===443?"HTTPS":"HTTP"} port ${p} for ${i}`,o);await TR(t,i,b,n,s,a,o,u,l,Tn(e.auth),r,e.loadBalancer)}catch(p){m("setup",`Setup failed: ${p}`,o),x.error(`Failed to setup reverse proxy: ${p.message}`),ec({domains:[i],hosts:typeof c==="boolean"?c:c?.hosts,certs:typeof c==="boolean"?c:c?.certs,verbose:o,vitePluginUsage:a})}}function Nw(e,t=80,r=443,i,n,s){m("redirect",`Starting HTTP redirect server on port ${t}`,e);let o=Qa.createServer((c,a)=>{let l=c.url?c.url.split("?",1)[0]:"";if(l.startsWith("/.well-known/acme-challenge/")){if(n){let d=n.challengeStore.handlePath(l);if(d!==void 0){m("redirect",`Serving on-demand ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(i){let d=xa(i,l);if(d!=null){m("redirect",`Serving ACME challenge ${l}`,e),a.writeHead(200,{"content-type":"text/plain"}),a.end(d);return}}if(n){a.writeHead(404,{"content-type":"text/plain"}),a.end("challenge not found");return}}let u=c.headers.host||"",f=u.includes(":")?u.slice(0,u.indexOf(":")):u;if(n&&f&&!n.hasCert(f)&&(!s||s(f)))n.ensureCert(f).catch(()=>{});let h=r===443?f:`${f}:${r}`;m("redirect",`Redirecting request from ${u}${c.url} to https://${h}`,e),a.writeHead(301,{Location:`https://${h}${c.url}`}),a.end()}).listen(t);Yn.add(o),m("redirect","HTTP redirect server started",e)}function Dw(e){let t={...jt,...e};if(m("proxy",`Starting proxy with options: ${tr(t)}`,t?.verbose),t.viaDaemon){if(!t.from||!t.to){x.error("viaDaemon mode requires both `from` and `to`");return}Hf({proxies:[{id:t.id,from:t.from,to:t.to,path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}],verbose:t.verbose}).catch((a)=>{x.error(`Failed to register with rpx daemon: ${a.message}`),Y.exit(1)});return}let r=t.to||"",i=r.split(".").pop()?.toLowerCase()||"",n=Y.platform==="darwin"&&r&&!r.includes("localhost")&&!r.includes("127.0.0.1"),s=["dev","app","page","new","day","foo"],o=["test","localhost","local","example","invalid"];if(n&&s.includes(i)&&t?.verbose)x.warn(`The .${i} TLD may not work reliably for local development`),x.info(` Google owns .${i} with HSTS preloading, which can bypass local DNS`),x.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(n)Promise.resolve().then(() => (Kn(),La)).then(({setupDevelopmentDns:a})=>{a({domains:[r],verbose:t.verbose}).then((l)=>{if(l)Promise.resolve().then(()=>{if(t.verbose)if(o.includes(i))x.success(`DNS server started for .${i} domains`);else x.success(`DNS server started for .${i} domains (hosts file entry also added)`)});else m("dns",`Could not start DNS server - ${r} may not resolve in browser`,t.verbose)})}).catch((a)=>{m("dns",`Failed to start DNS server: ${a}`,t.verbose)});let c={from:t.from,to:t.to,cleanUrls:t.cleanUrls,https:$n(t),cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,changeOrigin:t.changeOrigin,verbose:t.verbose,regenerateUntrustedCerts:t.regenerateUntrustedCerts};m("proxy",`Server options: ${tr(c)}`,t.verbose),Ow(c).catch((a)=>{m("proxy",`Failed to start proxy: ${a}`,t.verbose),x.error(`Failed to start proxy: ${a.message}`),ec({domains:[t.to],hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose})})}function RR(e){return e?.verbose||!1}function Gf(e){if(e?.hostsManagement===!1)return!1;let t=e?.cleanup;if(t===!1)return!1;if(t&&typeof t==="object"&&t.hosts===!1)return!1;return!0}async function Fw(e){let t={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(e)t={...t,...e};let r=RR(t),i=Gf(t);if(m("config",`Starting with config: ${tr(t,2)}`,r),m("config",`Is multi-proxy? ${"proxies"in t}`,r),m("config",`Hosts management enabled? ${i}`,r),t.viaDaemon){let T="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((S)=>({id:S.id,from:S.from,to:S.to,path:S.path,cleanUrls:S.cleanUrls??t.cleanUrls,changeOrigin:S.changeOrigin??t.changeOrigin,pathRewrites:S.pathRewrites})):[{id:t.id,from:t.from,to:t.to??"rpx.localhost",path:t.path,cleanUrls:t.cleanUrls,changeOrigin:t.changeOrigin,pathRewrites:t.pathRewrites}];await Hf({proxies:T,verbose:r});return}if("proxies"in t&&Array.isArray(t.proxies)){m("servers",`Found ${t.proxies.length} proxies in config`,r);for(let v of t.proxies)if(v.start){let T=`${v.from}-${v.to}`;try{m("watch",`Starting command for ${T} with command: ${v.start.command}`,r),x.info(`Starting command for ${T}...`),await qa.startProcess(T,v.start,r);let S=Ir(v.from),D=new URL(S.startsWith("http")?S:`http://${S}`),W=D.hostname||"localhost",Xe=Number(D.port)||80;try{await zn(W,Xe,r),m("watch",`Dev server is ready at ${W}:${Xe}`,r)}catch(at){m("watch",`Connection check failed, but continuing with proxy setup: ${at}`,r),x.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(S){throw m("watch",`Failed to start command for ${T}: ${S}`,r),Error(`Failed to start command for ${T}: ${S}`)}}else m("watch",`No start command for proxy ${v.from} -> ${v.to}`,r)}else if("start"in t&&t.start){m("watch","Found start command in single proxy config",r);let v=`${t.from}-${t.to}`;try{if(t.start)m("watch",`Starting command: ${t.start.command}`,r),await qa.startProcess(v,t.start,r);let T=Ir(t.from),S=new URL(T.startsWith("http")?T:`http://${T}`),D=S.hostname||"localhost",W=Number(S.port)||80;try{await zn(D,W,r),m("watch",`Dev server is ready at ${D}:${W}`,r)}catch(Xe){m("watch",`Connection check failed, but continuing with proxy setup: ${Xe}`,r),x.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw m("watch",`Failed to run start command: ${T}`,r),Error(`Failed to run start command: ${T}`)}}else m("watch","No start command found in config",r);let n="proxies"in t&&Array.isArray(t.proxies)?t.proxies[0]?.to:("to"in t)?t.to:"rpx.localhost";if(Y.platform!=="win32"&&(t.https||i)){if(!pr())try{m("sudo","Pre-acquiring sudo credentials for privileged operations",r),SR("sudo -v",{stdio:"inherit"})}catch{m("sudo","Could not pre-acquire sudo credentials",r)}}let s=[];if(t.productionCerts){if(s=await Dn(t.productionCerts,r),s.length>0)m("ssl",`Using ${s.length} production SNI cert(s): ${s.map((v)=>v.serverName).join(", ")}`,r)}if(t.https){let v=s.length>0?null:await xr(t);if(!v&&s.length===0){if(m("ssl",`No valid or trusted certificates found for ${n}, generating new ones`,t.verbose),await bn(t),v=await xr(t),!v)throw Error(`Failed to load SSL certificates after generation for ${n}`)}else m("ssl",`Using existing and trusted certificates for ${n}`,t.verbose);t._cachedSSLConfig=v}let o="proxies"in t&&Array.isArray(t.proxies)?t.proxies.map((v)=>({...v,https:t.https,cleanup:t.cleanup,cleanUrls:v.cleanUrls??("cleanUrls"in t?t.cleanUrls:!1),vitePluginUsage:t.vitePluginUsage,changeOrigin:v.changeOrigin??t.changeOrigin,verbose:r,_cachedSSLConfig:t._cachedSSLConfig})):[{from:"from"in t?t.from:"localhost:5173",to:"to"in t?t.to:"rpx.localhost",cleanUrls:"cleanUrls"in t?t.cleanUrls:!1,https:t.https,cleanup:t.cleanup,vitePluginUsage:t.vitePluginUsage,start:"start"in t?t.start:void 0,changeOrigin:t.changeOrigin,auth:"auth"in t?t.auth:void 0,verbose:r,_cachedSSLConfig:t._cachedSSLConfig}],c=o.map((v)=>v.to||"rpx.localhost"),a=s.length>0?s:t._cachedSSLConfig??null,l=c.filter((v)=>v&&!v.includes("localhost")&&!v.includes("127.0.0.1")),u=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"],h=[...new Set(l.map((v)=>v.split(".").pop()?.toLowerCase()))],d=h.filter((v)=>!!v&&u.includes(v));if(d.length>0&&r)x.warn(`The following TLDs may not work reliably for local development: ${d.map((v)=>`.${v}`).join(", ")}`),x.info(" These TLDs have HSTS preloading which can bypass local DNS"),x.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(i&&Y.platform==="darwin"&&l.length>0){let{setupDevelopmentDns:v}=await Promise.resolve().then(() => (Kn(),La));if(await v({domains:l,verbose:r})){if(r)if(h.every((D)=>!!D&&f.includes(D)))x.success(`DNS server started for ${h.map((D)=>`.${D}`).join(", ")} domains`);else x.success(`DNS server started for ${h.map((D)=>`.${D}`).join(", ")} domains (hosts file entries also added)`)}else m("dns","Could not start DNS server - custom domains may not resolve",r)}let y=async()=>{m("cleanup","Starting cleanup handler",t.verbose);try{let{tearDownDevelopmentDns:v}=await Promise.resolve().then(() => (Kn(),La));await v({verbose:t.verbose})}catch(v){m("cleanup",`Error stopping DNS server: ${v}`,t.verbose)}try{await qa.stopAll(t.verbose)}catch(v){m("cleanup",`Error stopping processes: ${v}`,t.verbose)}await ec({domains:c,hosts:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.hosts,certs:typeof t.cleanup==="boolean"?t.cleanup:t.cleanup?.certs,verbose:t.verbose||!1})};Y.on("SIGINT",y),Y.on("SIGTERM",y);let g=t.singlePortMode===!0,p=t.httpsPort??443,w=t.httpPort??80,b=t.originGuard?Ew(t.originGuard):null,P=!!a&&(o.length>1||g||s.length>0),R=!a&&g&&o.length>0;if(P&&a){m("proxies",`Creating shared HTTPS server for ${o.length} domains on port ${p}`,r);let v=await Pw(o,i,r),T=null,S=t.onDemandTls,D=S?.enabled?new Ii({config:S,certsDir:S.certsDir??t.productionCerts?.certsDir??Aw.join(Za.homedir(),".stacks","rpx","on-demand-certs"),initial:s,verbose:r,onCertAdded:(Ie)=>{if(Fn()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",r),setTimeout(()=>Y.kill(Y.pid,"SIGTERM"),10).unref();else at(Ie)}}):null,W=null,Xe=!1;async function at(Ie){if(W=Ie,Xe)return;Xe=!0;try{while(W){let ct=W;if(W=null,m("proxies",`rebuilding :${p} with ${ct.length} SNI cert(s)`,r),T)Yn.delete(T),T.stop(!1);let Ue=!1;for(let O=0;!Ue&&O<60;O++){let We=Ja({routeEntries:v,listenPort:p,sslConfig:ct,originGuard:b,verbose:r});if(We){T=We,Ue=!0;break}await new Promise((Vi)=>setTimeout(Vi,Math.min(25*2**Math.min(O,4),500)))}if(!Ue)x.error(`rpx: CRITICAL — could not rebind :${p} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{Xe=!1}}if(!await Cr(w,"0.0.0.0",r)){let Ie=new Set(v.map((Ue)=>Ue.host)),ct=(Ue)=>Ie.has(Ue)||[...Ie].some((O)=>Or(Ue,O));Nw(r,w,p,t.acmeChallengeWebroot,D,ct)}if(await Cr(p,"0.0.0.0",r)){if(m("proxies",`Port ${p} is already in use, cannot start shared proxy`,r),r)x.warn(`Port ${p} is in use. Shared HTTPS proxy cannot start.`);return}let sr=D&&D.sniEntries().length>0?D.sniEntries():a;if(T=Ja({routeEntries:v,listenPort:p,sslConfig:sr,originGuard:b,verbose:r}),!T){x.error(`Shared HTTPS proxy failed to bind :${p}; not exiting`);return}}else if(R){m("proxies",`Creating shared HTTP server for ${o.length} domains on port ${w}`,r);let v=await Pw(o,i,r);if(await Cr(w,"0.0.0.0",r)){if(m("proxies",`Port ${w} is already in use, cannot start shared proxy`,r),r)x.warn(`Port ${w} is in use. Shared HTTP proxy cannot start.`);return}if(!Ja({routeEntries:v,listenPort:w,sslConfig:null,originGuard:b,verbose:r})){x.error(`Shared HTTP proxy failed to bind :${w}; not exiting`);return}}else for(let v of o)try{let T=v.to||"rpx.localhost";m("proxy",`Starting proxy for ${T} with SSL config: ${!!a}`,v.verbose),await Ow({from:v.from||"localhost:5173",to:T,cleanUrls:v.cleanUrls||!1,https:v.https||!1,cleanup:v.cleanup||!1,vitePluginUsage:v.vitePluginUsage||!1,verbose:v.verbose||!1,_cachedSSLConfig:t._cachedSSLConfig,changeOrigin:v.changeOrigin||!1,loadBalancer:v.loadBalancer,auth:v.auth,path:v.path,pathRewrites:v.pathRewrites})}catch(T){m("proxies",`Failed to start proxy for ${v.to}: ${T}`,v.verbose),x.error(`Failed to start proxy for ${v.to}:`,T)}}async function Pw(e,t,r){let i=[],n=new Set;for(let s of e){let o=s.to||"rpx.localhost",c=s.cleanUrls||!1,a=s.path,l=rr(a),u=Tn(s.auth);if(s.redirect){let f=Ey(s.redirect);i.push({host:o,path:a,route:{redirect:f,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → redirect ${f.status} ${f.to}${u?" (auth)":""}`,r)}else if(s.static)i.push({host:o,path:a,route:{static:ba(s.static,c),cleanUrls:c,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → static ${typeof s.static==="string"?s.static:s.static.dir}${u?" (auth)":""}`,r);else{let f=Ir(s.from),h=new URL(f.startsWith("http")?f:`http://${f}`),d=xn(s.from??h.host,s.loadBalancer);Sn(d),Xa.add(d),i.push({host:o,path:a,route:{sourceHost:h.host,upstreamPool:d,cleanUrls:c,changeOrigin:s.changeOrigin||!1,pathRewrites:s.pathRewrites,basePath:l,auth:u}}),m("proxies",`Route: ${o}${a??""} → ${h.host}${u?" (auth)":""}`,r)}if(n.has(o))continue;if(n.add(o),t&&!ai(o)&&!o.includes("localhost")&&!o.includes("127.0.0.1"))try{if(!(await _n([o],r))[0])await In([o],r)}catch{m("hosts",`Could not add hosts entry for ${o}`,r)}}return i}var Vn=null;function Bw(){if(Y.env.RPX_BIND_HOSTNAME)return Y.env.RPX_BIND_HOSTNAME;if(Vn)return Vn;try{Vn=Object.values(Za.networkInterfaces()).flat().some((r)=>r&&r.family==="IPv6")?"::":"0.0.0.0"}catch{Vn="0.0.0.0"}return Vn}function Ja(e){let{routeEntries:t,listenPort:r,sslConfig:i,originGuard:n,verbose:s}=e,o=kn(t),c=Rn((u,f)=>On(o,u,f),s),a=n?(u,f)=>n(u)??c(u,f):c,l=An(s);try{let u=Bun.serve({port:r,hostname:Bw(),reusePort:wn(),...i?{tls:jr(Array.isArray(i)?i.map((f)=>({serverName:f.serverName,key:f.key,cert:f.cert})):{key:i.key,cert:i.cert,ca:i.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(f,h){return a(f,h)},websocket:l,error(f){return m("server",`Shared proxy server error: ${f}`,s),new Response(`Server Error: ${f.message}`,{status:500})}});return Yn.add(u),m("proxies",`Shared ${i?"HTTPS":"HTTP"} proxy listening on port ${r} for ${o.size} domains`,s),u}catch(u){return m("proxies",`Failed to start shared proxy: ${u}`,s),console.error("Failed to start shared proxy:",u),null}}function AR(e){if(e?.vitePluginUsage||!e?.verbose)return;if(console.log(""),console.log(` ${Nt.green(Nt.bold("rpx"))} ${Nt.green(`v${Hn}`)}`),console.log(` ${Nt.green("➜")} ${Nt.dim(e?.from??"")} ${Nt.dim("➜")} ${Nt.cyan(e?.ssl?`https://${e?.to}`:`http://${e?.to}`)}`),e?.listenPort!==(e?.ssl?443:80))console.log(` ${Nt.green("➜")} Listening on port ${e?.listenPort}`);if(e?.cleanUrls)console.log(` ${Nt.green("➜")} Clean URLs enabled`)}he();Me.chdir(OR(kR(NR(import.meta.url)),".."));var je=new fc("rpx");je.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(e)=>{if(!e?.from||!e.to)return Fw(jt);let t={from:e.from,to:e.to,https:{keyPath:e.keyPath,certPath:e.certPath,caCertPath:e.caCertPath},cleanup:{certs:e.certsCleanup||!1,hosts:e.hostsCleanup||!1},verbose:e.verbose||!1,changeOrigin:e.changeOrigin||!1,singlePortMode:e.singlePortMode||!1,httpPort:e.httpPort!==void 0?Number(e.httpPort):void 0,httpsPort:e.httpsPort!==void 0?Number(e.httpsPort):void 0,viaDaemon:e.viaDaemon||!1,id:e.id};if(e.startCommand){let r={command:e.startCommand};if(e.startCwd)r.cwd=e.startCwd;if(e.startEnv)try{r.env=JSON.parse(e.startEnv)}catch(i){console.error("Failed to parse start-env JSON:",i),Me.exit(1)}t.start=r}return Dw(t)});je.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{let r=ha(jt)?jt.proxies.find((i)=>i.to===e||`${i.from}-${i.to}`===e):jt.to===e?jt:null;if(!r?.start)console.error(`No watch configuration found for proxy: ${e}`),Me.exit(1);try{await Va.startProcess(e,r.start,t.verbose),console.log(`Started dev server for ${e}`)}catch(i){console.error(`Failed to start dev server for ${e}:`,i),Me.exit(1)}});je.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(e,t)=>{try{await Va.stopProcess(e,t.verbose),console.log(`Stopped dev server for ${e}`)}catch(r){console.error(`Failed to stop dev server for ${e}:`,r),Me.exit(1)}});je.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(e)=>{try{await Va.stopAll(e.verbose),console.log("Stopped all dev servers")}catch(t){console.error("Failed to stop all dev servers:",t),Me.exit(1)}});async function Lw(e){let r={...(await Ld().catch(()=>null))?.onDemand??{},enabled:!0};if(e){let i=e.split(",").map((n)=>n.trim()).filter(Boolean);if(i.length>0)r.roots=i}return r}je.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(e)=>{try{let t=e.onDemand?await Lw(e.roots):void 0;await(await bw({rpxDir:e.rpxDir,registryDir:e.registryDir,httpsPort:typeof e.httpsPort==="string"?Number.parseInt(e.httpsPort,10):e.httpsPort,httpPort:typeof e.httpPort==="string"?Number.parseInt(e.httpPort,10):e.httpPort,hostname:e.hostname,productionCerts:e.certsDir?{certsDir:e.certsDir}:void 0,workers:e.workers===void 0?void 0:typeof e.workers==="string"?Number.parseInt(e.workers,10):e.workers,onDemandSites:t,verbose:e.verbose??!0})).done,Me.exit(0)}catch(t){console.error(`Failed to start rpx daemon: ${t.message}`),Me.exit(1)}});je.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(e)=>{let t=typeof e.timeout==="string"?Number.parseInt(e.timeout,10):e.timeout,r=await $w({rpxDir:e.rpxDir,timeoutMs:t,forceAfterTimeout:e.force!==!1,verbose:e.verbose});if(!r.stopped&&r.pid===null){console.log("rpx daemon is not running");return}if(!r.stopped){console.log(`rpx daemon pid=${r.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${r.pid} stopped${r.forced?" (SIGKILL)":""}`)});je.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(e)=>{let t=e.rpxDir??Pe(),r=await Tr(t),i=await Ua(t),n=e.registryDir,s=await wt(n).catch(()=>[]);if(e.json){console.log(JSON.stringify({running:i,pid:r,pidFile:Pr(t),rpxDir:t,registryDir:n??st(),entries:s},null,2));return}if(!i){if(console.log("rpx daemon: not running"),r!==null)console.log(`(stale pid file at ${Pr(t)} → pid ${r})`)}else console.log(`rpx daemon: running (pid=${r})`),console.log(`pid file: ${Pr(t)}`);if(console.log(`registry: ${n??st()}`),s.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${s.length}):`);for(let o of s){let c=o.pid!==void 0?`, pid=${o.pid}`:"";console.log(` https://${o.to} → ${o.from} (id=${o.id}${c})`)}});je.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(e)=>{if(!e.id||!e.from||!e.to)console.error("rpx register requires --id, --from, and --to"),Me.exit(1);if(!Sr(e.id))console.error(`invalid id: ${JSON.stringify(e.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),Me.exit(1);try{await _i({id:e.id,from:e.from,to:e.to,cwd:e.cwd,createdAt:new Date().toISOString(),cleanUrls:e.cleanUrls,changeOrigin:e.changeOrigin},e.registryDir,e.verbose)}catch(t){console.error(`failed to write registry entry: ${t.message}`),Me.exit(1)}if(e.skipSpawn){console.log(`registered ${e.to} → ${e.from} (daemon spawn skipped)`);return}try{let t=await Wa({rpxDir:e.rpxDir,verbose:e.verbose}),r=t.spawned?"spawned":"attached to";console.log(`registered https://${e.to} → ${e.from} (${r} daemon pid=${t.pid})`)}catch(t){console.error(`registered entry but daemon spawn failed: ${t.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),Me.exit(1)}});je.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(e,t)=>{if(!Sr(e))console.error(`invalid id: ${JSON.stringify(e)}`),Me.exit(1);let r=await Ef(e,t.registryDir,t.verbose);if(!r){console.log(`no registry entry for id=${e}`);return}await Ur(e,t.registryDir,t.verbose),console.log(`unregistered ${r.to} (id=${e})`)});je.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(e)=>{let t=e.rpxDir??Pe();if(await Ua(t)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await xw({rpxDir:t,verbose:e.verbose}),console.log("DNS reconcile complete")});je.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(e)=>{let t=await Lw(e.roots),r=Wd(t),i=await wt(e.registryDir).catch(()=>[]),n=new Set(i.map((c)=>c.to)),s=r.map((c)=>({host:c.host,dir:c.dir,command:c.command,source:c.source,live:n.has(c.host)}));if(e.json){console.log(JSON.stringify(s,null,2));return}let o=t.roots??["~/Code"];if(s.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${o.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${s.length}) — scanned ${o.join(", ")}:`);for(let c of s)console.log(` ${c.live?"●":"○"} https://${c.host} ${c.live?"(live)":"(idle)"}`),console.log(` ${c.command} ${c.dir}`)});je.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(e,t)=>{let{readFile:r}=await import("node:fs/promises"),{join:i}=await import("node:path"),n=t.rpxDir??Pe(),s=i(n,"sites",`${Ms(e.split(":")[0])}.log`),o;try{o=await r(s,"utf8")}catch{console.log(`no log for ${e} (it may not have been booted yet) — looked in ${s}`);return}let c=t.lines===void 0?void 0:typeof t.lines==="string"?Number.parseInt(t.lines,10):t.lines,a=o.split(`
|
|
329
|
+
`);Me.stdout.write((c&&c>0?a.slice(-c):a).join(`
|
|
330
|
+
`))});je.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(Hn)});je.version(Hn);je.help();je.run();
|