@stacksjs/rpx 0.11.13 → 0.11.15
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 +178 -174
- package/dist/chunk-0zdj72ps.js +161 -0
- package/dist/{chunk-zs1tyy8z.js → chunk-hf6e07v4.js} +1 -1
- package/dist/{chunk-747af2w4.js → chunk-kv17r01q.js} +1 -1
- package/dist/chunk-pjwm8py7.js +1 -0
- package/dist/daemon-runner.d.ts +3 -2
- package/dist/daemon.d.ts +7 -1
- package/dist/host-match.d.ts +23 -0
- package/dist/index.d.ts +15 -2
- package/dist/index.js +6 -6
- package/dist/on-demand.d.ts +40 -0
- package/dist/proxy-handler.d.ts +18 -3
- package/dist/registry.d.ts +3 -2
- package/dist/sni.d.ts +20 -0
- package/dist/static-files.d.ts +46 -0
- package/dist/types.d.ts +64 -1
- package/package.json +2 -2
- package/src/daemon-runner.ts +12 -4
- package/src/daemon.ts +154 -21
- package/src/host-match.ts +52 -0
- package/src/index.ts +19 -2
- package/src/on-demand.ts +264 -0
- package/src/proxy-handler.ts +184 -21
- package/src/registry.ts +11 -3
- package/src/sni.ts +93 -0
- package/src/start.ts +66 -19
- package/src/static-files.ts +201 -0
- package/src/types.ts +138 -1
- package/dist/chunk-kbnzcycw.js +0 -1
- package/dist/chunk-pncxrxde.js +0 -157
package/dist/bin/cli.js
CHANGED
|
@@ -1,250 +1,254 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
3
|
#!/usr/bin/env bun
|
|
4
|
-
import{createRequire as uj}from"node:module";var bj=Object.defineProperty;var ij=($)=>$;function cj($,w){this[$]=ij.bind(null,w)}var UZ=($,w)=>{for(var A in w)bj($,A,{get:w[A],enumerable:!0,configurable:!0,set:cj.bind(w,A)})};var X$=($,w)=>()=>($&&(w=$($=0)),w);var c=uj(import.meta.url);import{existsSync as KZ,statSync as RZ}from"fs";import{existsSync as gz,mkdirSync as n5,readdirSync as m5,readFileSync as lz,writeFileSync as d5}from"fs";import{homedir as Cw}from"os";import{dirname as p5,resolve as a$}from"path";import uA from"process";import{existsSync as MZ,statSync as IZ}from"fs";import{existsSync as BY,mkdirSync as pz,readdirSync as tz,writeFileSync as rz}from"fs";import{homedir as Lw}from"os";import{dirname as yZ,resolve as D$}from"path";import Ew from"process";import{join as az,relative as sz,resolve as CZ}from"path";import SA from"process";import{existsSync as WW,mkdirSync as J6,readdirSync as U6,writeFileSync as Y6}from"fs";import{homedir as dU}from"os";import{dirname as W6,resolve as _$}from"path";import I1 from"process";import{join as oz,relative as ez,resolve as LZ}from"path";import VA from"process";import{existsSync as BW,mkdirSync as z6,readdirSync as H6,writeFileSync as T6}from"fs";import{dirname as h6,resolve as OA}from"path";import EY from"process";import{Buffer as p0}from"buffer";import{createCipheriv as $9,createDecipheriv as w9,randomBytes as gU}from"crypto";import{closeSync as lU,createReadStream as SZ,createWriteStream as A9,existsSync as pU,fsyncSync as VZ,openSync as OZ,writeFileSync as J9}from"fs";import{access as U9,constants as XZ,mkdir as Y9,readdir as ZA,rename as _Z,stat as Sw,unlink as WA,writeFile as tU}from"fs/promises";import{join as Vw}from"path";import N$ from"process";import{pipeline as f9}from"stream/promises";import{createGzip as DZ}from"zlib";import Ow from"process";import y0 from"process";import{Buffer as R0}from"buffer";import{createCipheriv as Z9,createDecipheriv as W9,randomBytes as rU}from"crypto";import{closeSync as aU,createReadStream as kZ,createWriteStream as B9,existsSync as BA,fsyncSync as QZ,openSync as xZ,writeFileSync as E9}from"fs";import{access as F9,constants as PZ,mkdir as j9,readdir as EA,rename as bZ,stat as Xw,unlink as FA,writeFile as sU}from"fs/promises";import{isAbsolute as z9,join as _w,resolve as H9}from"path";import V from"process";import{pipeline as T9}from"stream/promises";import{createGzip as iZ}from"zlib";import Dw from"process";import C0 from"process";import jA from"process";import{existsSync as zA}from"fs";import{resolve as oU}from"path";import{existsSync as G9}from"fs";import{existsSync as h9,readdirSync as q9}from"fs";import{extname as eU,resolve as cZ}from"path";import N9 from"process";import{join as K9,relative as R9,resolve as uZ}from"path";import XA from"process";import{Buffer as M0}from"buffer";import{createCipheriv as M9,createDecipheriv as I9,randomBytes as $Y}from"crypto";import{closeSync as wY,createReadStream as vZ,createWriteStream as y9,existsSync as HA,fsyncSync as nZ,openSync as mZ,writeFileSync as C9}from"fs";import{access as L9,constants as dZ,mkdir as S9,readdir as TA,rename as gZ,stat as kw,unlink as GA,writeFile as AY}from"fs/promises";import{isAbsolute as V9,join as Qw,resolve as O9}from"path";import O from"process";import{pipeline as X9}from"stream/promises";import{createGzip as lZ}from"zlib";import xw from"process";import L0 from"process";import qA from"process";import{existsSync as NA}from"fs";import{resolve as WY}from"path";import{existsSync as aH}from"fs";class fW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!KZ($))return!0;return RZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=KZ(A)?RZ(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class ZW{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function k9($,w){this[$]=D9.bind(null,w)}class MY{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!MZ($))return!0;return IZ($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=MZ(A)?IZ(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class IY{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function P9($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function b9($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function i9($){return $.getStats().size*2}function yY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let J=[...w];for(let U of $)if(r(U)&&"name"in U){if(!J.find((f)=>r(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((f)=>r(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>_A(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!r(w)||!r($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(r(U)&&r(A[J]))A[J]=yY(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&r(U[0])&&r(A[J][0])){let Y=[...U];for(let f of A[J])if(r(f)&&"name"in f){if(!Y.find((Z)=>r(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(r(f)&&"path"in f){if(!Y.find((Z)=>r(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>_A(W,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function _A($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!_A($[A],w[A]))return!1;return!0}if(r($)&&r(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!_A($[U],w[U]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function c9($,w){if(!BW($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return yY(w,J)}catch{return null}}catch{return null}}async function u9({name:$="",cwd:w,defaultConfig:A}){let J=w||EY.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=OA(J,`${f}${W}`),B=await c9(Z,A);if(B!==null)return B}try{let f=OA(J,"package.json");if(BW(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return yY(A,Z)}catch{}}}catch{}return A}function v9($,w={}){let A=VA.cwd();while(A.includes("storage"))A=LZ(A,"..");let J=LZ(A,$||"");if(w?.relative)return ez(VA.cwd(),J);return J}async function n9(){try{let $=await u9({name:"clarity",defaultConfig:MA,cwd:VA.cwd(),endpoint:"",headers:{}});return{...MA,...$}}catch{return MA}}function $$(){if(y0.env.NODE_ENV==="test"||y0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function m9(){if(y0.env.NODE_ENV==="test"||y0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof y0<"u"){let $=y0.type;if($==="renderer"||$==="worker")return!1;return!!(y0.versions&&(y0.versions.node||y0.versions.bun))}return!1}class FW{async format($){let w=await m9(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Ow.pid,hostname:w(),environment:Ow.env.NODE_ENV||"development",platform:Ow.platform,version:Ow.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ow.env.NODE_ENV||Ow.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class DA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...jY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new FW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??N$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...IA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...IA};return{...IA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:jY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await U9(this.config.logDirectory,XZ.F_OK|XZ.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Y9(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:p0.from($);try{if(!pU(this.currentLogFile))await tU(this.currentLogFile,"",{mode:420});if(U=OZ(this.currentLogFile,"a",420),J9(U,Z,{flag:"a"}),VZ(U),U!==void 0)lU(U),U=void 0;if((await Sw(this.currentLogFile)).size===0){if(await tU(this.currentLogFile,Z,{flag:"w",mode:420}),(await Sw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<f-1){let F=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let z=W*2**Y;await new Promise((j)=>setTimeout(j,z)),Y++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{lU(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Z){if(Y===f-1){let E=Z,F=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),Z}Y++;let B=W*2**(Y-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Vw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if($$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Z])=>Z.createdAt.getTime()-W.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[W]of U.slice(f))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return gU(16).toString("hex")}generateKey(){return gU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=gU(16),J=$9("aes-256-gcm",w,A),U=p0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:p0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=DZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(p0.from(p0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if($$())return;let $=await Sw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await ZA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await Sw(A).catch(()=>null))try{if(await _Z(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await WA(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await tU(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Sw(A).catch(()=>null))await _Z(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await ZA(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await WA(Vw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=SZ($),J=A9(w),U=DZ();await f9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),pU(this.currentLogFile))try{let $=OZ(this.currentLogFile,"r+");VZ($),lU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!$$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await ZA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await WA(Vw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=N$.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${g.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);if(this.fancy&&!$$()){let B=RW[$],E=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:g.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:g.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.error(F),W){let z=W.split(`
|
|
5
|
-
`);for(let
|
|
6
|
-
`;if(W)
|
|
7
|
-
`;
|
|
8
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy
|
|
9
|
-
`),
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!N$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if($$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await ZA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=Vw(this.config.logDirectory,J);if($.before)try{if((await Sw(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await WA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function RA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&u(w[0])&&"id"in w[0]&&w[0].id===3&&u(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(u(w)&&u($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(u($)&&"arr"in $&&Array.isArray($.arr)&&u(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&u(w[0])&&u($[0])){let J=[...w];for(let U of $)if(u(U)&&"name"in U){if(!J.find((f)=>u(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(u(U)&&"path"in U){if(!J.find((f)=>u(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>kA(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!u(w)||!u($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(u(U)&&u(A[J]))A[J]=RA(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&u(U[0])&&u(A[J][0])){let Y=[...U];for(let f of A[J])if(u(f)&&"name"in f){if(!Y.find((Z)=>u(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(u(f)&&"path"in f){if(!Y.find((Z)=>u(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>kA(W,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function CY($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:RA($,w);if(Array.isArray($))return A==="replace"?w:RA($,w);if(!u(w)||!u($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],f=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(f))if(A==="replace")J[U]=Y;else J[U]=RA(f,Y);else if(u(Y)&&u(f))J[U]=CY(f,Y,A);else J[U]=Y}return J}function kA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!kA($[A],w[A]))return!1;return!0}if(u($)&&u(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!kA($[U],w[U]))return!1}return!0}return!1}function u($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function hA($,w,A="replace"){if(!WW($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return CY(w,U,A)}catch{return null}}catch{return null}}function d9($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),j=`${J}_${F.map(z).join("_")}`,G=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)R$.info(`Checking environment variable ${j} for config ${$}.${F.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))Z[B]=Y(E,F);else{let T=I1.env[j]||I1.env[G];if(T!==void 0){if(A)R$.info(`Using environment variable ${T?j:G} for config ${$}.${F.join(".")}`);if(typeof E==="number")Z[B]=Number(T);else if(typeof E==="boolean")Z[B]=T.toLowerCase()==="true";else if(Array.isArray(E))try{let h=JSON.parse(T);if(Array.isArray(h))Z[B]=h;else Z[B]=T.split(",").map((q)=>q.trim())}catch{Z[B]=T.split(",").map((h)=>h.trim())}else Z[B]=T}}}return Z}return Y(U)}async function g9({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:f=!0,arrayStrategy:W="replace"}){let Z=f&&typeof U==="object"&&U!==null&&!Array.isArray(U)?d9($,U,Y):U,B=A||I1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(Y)R$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let F=[$,`.${$}`].filter(Boolean),z=[`${$}.config`,`.${$}.config`].filter(Boolean),j=w?[w,`.${w}`]:[],G=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([B,_$(B,"config"),_$(B,".config"),J?_$(B,J):void 0].filter(Boolean)));for(let h of T){if(Y)R$.info(`Searching for configuration in: ${h}`);let N=[_$(B,"config"),_$(B,".config")].concat(J?[_$(B,J)]:[]).includes(h)?[...F,...z,...j,...G]:[...z,...F,...G,...j];for(let R of N)for(let y of E){let C=_$(h,`${R}${y}`),L=await hA(C,Z,W);if(L!==null){if(Y)R$.success(`Configuration loaded from: ${C}`);return L}}}if($){let h=_$(dU(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)R$.info(`Checking user config directory: ${h}`);for(let N of q)for(let R of E){let y=_$(h,`${N}${R}`),C=await hA(y,Z,W);if(C!==null){if(Y)R$.success(`Configuration loaded from user config directory: ${y}`);return C}}}if($){let h=_$(dU(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)R$.info(`Checking user config directory for dotfile configs: ${h}`);for(let N of q)for(let R of E){let y=_$(h,`${N}${R}`),C=await hA(y,Z,W);if(C!==null){if(Y)R$.success(`Configuration loaded from user config directory dotfile: ${y}`);return C}}}if($){let h=dU(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)R$.info(`Checking user home directory for dotfile configs: ${h}`);for(let N of q)for(let R of E){let y=_$(h,`${N}${R}`),C=await hA(y,Z,W);if(C!==null){if(Y)R$.success(`Configuration loaded from user home directory: ${y}`);return C}}}try{let h=_$(B,"package.json");if(WW(h)){let q=await import(h),N=q[$];if(!N&&w){if(N=q[w],N&&Y)R$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)R$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return CY(Z,N,W)}catch(R){if(Y)R$.warn("Failed to merge package.json config:",R)}}}catch(h){if(Y)R$.warn("Failed to load package.json:",h)}if(Y)R$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function l9($,w={}){let A=SA.cwd();while(A.includes("storage"))A=CZ(A,"..");let J=CZ(A,$||"");if(w?.relative)return sz(SA.cwd(),J);return J}async function p9(){try{let $=await g9({name:"clarity",alias:"logging",defaultConfig:yA,cwd:SA.cwd()});return{...yA,...$||{}}}catch{return yA}}function f$(){if(C0.env.NODE_ENV==="test"||C0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function t9(){if(C0.env.NODE_ENV==="test"||C0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof C0<"u"){let $=C0.type;if($==="renderer"||$==="worker")return!1;return!!(C0.versions&&(C0.versions.node||C0.versions.bun))}return!1}class jW{async format($){let w=await t9(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Dw.pid,hostname:w(),environment:Dw.env.NODE_ENV||"development",platform:Dw.platform,version:Dw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dw.env.NODE_ENV||Dw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class QA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...zY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new jW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...CA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...CA};return{...CA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:zY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!f$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await F9(this.config.logDirectory,PZ.F_OK|PZ.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await j9(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!BA(this.currentLogFile))await sU(this.currentLogFile,"",{mode:420});if(U=xZ(this.currentLogFile,"a",420),E9(U,Z,{flag:"a"}),QZ(U),U!==void 0)aU(U),U=void 0;if((await Xw(this.currentLogFile)).size===0){if(await sU(this.currentLogFile,Z,{flag:"w",mode:420}),(await Xw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<f-1){let F=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let z=W*2**Y;await new Promise((j)=>setTimeout(j,z)),Y++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{aU(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Z){if(Y===f-1){let E=Z,F=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),Z}Y++;let B=W*2**(Y-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 _w(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 _w(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return _w(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Z])=>Z.createdAt.getTime()-W.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[W]of U.slice(f))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return rU(16).toString("hex")}generateKey(){return rU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=rU(16),J=Z9("aes-256-gcm",w,A),U=R0.isBuffer($)?$:R0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),B=R0.allocUnsafe(16+W+16);return A.copy(B,0),Y.copy(B,16),f.copy(B,16+Y.length),Z.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let J=iZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(R0.from(R0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f$())return;if(!this.shouldWriteToFile())return;let $=await Xw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await EA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await Xw(A).catch(()=>null))try{if(await bZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await FA(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await sU(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Xw(A).catch(()=>null))await bZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await EA(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await FA(_w(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=kZ($),J=B9(w),U=iZ();await T9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),BA(this.currentLogFile))try{let $=xZ(this.currentLogFile,"r+");QZ($),aU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await EA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await FA(_w(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?D.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f$())return!1;let $=typeof V.env.NO_COLOR<"u",w=V.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof V.stderr<"u"&&V.stderr.isTTY||typeof V.stdout<"u"&&V.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=V.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${D.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=D.underline(D.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>D.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>D.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>D.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>D.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>D.strikethrough(J)),w}supportsHyperlinks(){if(f$())return!1;let $=V.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=V.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(z9(w)||w.startsWith("./")||w.startsWith("../"))w=H9(w);else return null;return BA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);let{consoleText:Z,fileText:B}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":MW[$],z=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:D.gray(Z),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:D.green(Z),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.error(j),W){let G=W.split(`
|
|
13
|
-
`);for(let
|
|
4
|
+
import{createRequire as cF}from"node:module";var PF=Object.defineProperty;var iF=($)=>$;function bF($,w){this[$]=iF.bind(null,w)}var nJ=($,w)=>{for(var A in w)PF($,A,{get:w[A],enumerable:!0,configurable:!0,set:bF.bind(w,A)})};var K$=($,w)=>()=>($&&(w=$($=0)),w);var c=cF(import.meta.url);import{existsSync as YW,statSync as fW}from"fs";import{existsSync as dz,mkdirSync as hR,readdirSync as HR,readFileSync as lz,writeFileSync as GR}from"fs";import{homedir as xw}from"os";import{dirname as qR,resolve as e$}from"path";import YY from"process";import{existsSync as XW,statSync as UW}from"fs";import{existsSync as kX,mkdirSync as gz,readdirSync as tz,writeFileSync as pz}from"fs";import{homedir as Pw}from"os";import{dirname as JW,resolve as Z$}from"path";import Hw from"process";import{join as rz,relative as az,resolve as WW}from"path";import dA from"process";import{existsSync as lW,mkdirSync as QR,readdirSync as _R,writeFileSync as DR}from"fs";import{homedir as zX}from"os";import{dirname as xR,resolve as k$}from"path";import Z1 from"process";import{join as sz,relative as oz,resolve as BW}from"path";import lA from"process";import{existsSync as gW,mkdirSync as uR,readdirSync as nR,writeFileSync as vR}from"fs";import{dirname as dR,resolve as gA}from"path";import ZX from"process";import{Buffer as o0}from"buffer";import{createCipheriv as ez,createDecipheriv as $2,randomBytes as hX}from"crypto";import{closeSync as HX,createReadStream as EW,createWriteStream as w2,existsSync as GX,fsyncSync as jW,openSync as TW,writeFileSync as A2}from"fs";import{access as Y2,constants as FW,mkdir as f2,readdir as IA,rename as zW,stat as iw,unlink as CA,writeFile as KX}from"fs/promises";import{join as bw}from"path";import y$ from"process";import{pipeline as X2}from"stream/promises";import{createGzip as hW}from"zlib";import cw from"process";import O0 from"process";import{Buffer as C0}from"buffer";import{createCipheriv as U2,createDecipheriv as J2,randomBytes as RX}from"crypto";import{closeSync as qX,createReadStream as HW,createWriteStream as W2,existsSync as SA,fsyncSync as GW,openSync as KW,writeFileSync as B2}from"fs";import{access as E2,constants as RW,mkdir as j2,readdir as LA,rename as qW,stat as uw,unlink as OA,writeFile as NX}from"fs/promises";import{isAbsolute as T2,join as nw,resolve as F2}from"path";import O from"process";import{pipeline as z2}from"stream/promises";import{createGzip as NW}from"zlib";import vw from"process";import V0 from"process";import VA from"process";import{existsSync as QA}from"fs";import{resolve as yX}from"path";import{existsSync as h2}from"fs";import{existsSync as H2,readdirSync as G2}from"fs";import{extname as MX,resolve as yW}from"path";import K2 from"process";import{join as R2,relative as q2,resolve as MW}from"path";import tA from"process";import{Buffer as S0}from"buffer";import{createCipheriv as N2,createDecipheriv as y2,randomBytes as IX}from"crypto";import{closeSync as CX,createReadStream as IW,createWriteStream as M2,existsSync as _A,fsyncSync as CW,openSync as SW,writeFileSync as I2}from"fs";import{access as C2,constants as LW,mkdir as S2,readdir as DA,rename as OW,stat as mw,unlink as kA,writeFile as SX}from"fs/promises";import{isAbsolute as L2,join as dw,resolve as O2}from"path";import V from"process";import{pipeline as V2}from"stream/promises";import{createGzip as VW}from"zlib";import lw from"process";import Q0 from"process";import xA from"process";import{existsSync as PA}from"fs";import{resolve as DX}from"path";import{existsSync as rh}from"fs";class mW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!YW($))return!0;return fW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=YW(A)?fW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class dW{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function D2($,w){this[$]=_2.bind(null,w)}class gX{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!XW($))return!0;return UW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=XW(A)?UW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class tX{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function x2($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function P2($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function i2($){return $.getStats().size*2}function pX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&a(w[0])&&"id"in w[0]&&w[0].id===3&&a(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(a(w)&&a($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(a($)&&"arr"in $&&Array.isArray($.arr)&&a(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&a(w[0])&&a($[0])){let Y=[...w];for(let f of $)if(a(f)&&"name"in f){if(!Y.find((U)=>a(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(a(f)&&"path"in f){if(!Y.find((U)=>a(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>pA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!a(w)||!a($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(a(f)&&a(A[Y]))A[Y]=pX(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&a(f[0])&&a(A[Y][0])){let X=[...f];for(let U of A[Y])if(a(U)&&"name"in U){if(!X.find((J)=>a(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(a(U)&&"path"in U){if(!X.find((J)=>a(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>pA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function pA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!pA($[A],w[A]))return!1;return!0}if(a($)&&a(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!pA($[f],w[f]))return!1}return!0}return!1}function a($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function b2($,w){if(!gW($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return pX(w,Y)}catch{return null}}catch{return null}}async function c2({name:$="",cwd:w,defaultConfig:A}){let Y=w||ZX.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=gA(Y,`${U}${W}`),B=await b2(J,A);if(B!==null)return B}try{let U=gA(Y,"package.json");if(gW(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return pX(A,J)}catch{}}}catch{}return A}function u2($,w={}){let A=lA.cwd();while(A.includes("storage"))A=BW(A,"..");let Y=BW(A,$||"");if(w?.relative)return oz(lA.cwd(),Y);return Y}async function n2(){try{let $=await c2({name:"clarity",defaultConfig:cA,cwd:lA.cwd(),endpoint:"",headers:{}});return{...cA,...$}}catch{return cA}}function A$(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function v2(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof O0<"u"){let $=O0.type;if($==="renderer"||$==="worker")return!1;return!!(O0.versions&&(O0.versions.node||O0.versions.bun))}return!1}class pW{async format($){let w=await v2(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:cw.pid,hostname:w(),environment:cw.env.NODE_ENV||"development",platform:cw.platform,version:cw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:cw.env.NODE_ENV||cw.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;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new pW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??y$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...uA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...uA};return{...uA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await Y2(this.config.logDirectory,FW.F_OK|FW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await f2(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:o0.from($);try{if(!GX(this.currentLogFile))await KX(this.currentLogFile,"",{mode:420});if(f=TW(this.currentLogFile,"a",420),A2(f,J,{flag:"a"}),jW(f),f!==void 0)HX(f),f=void 0;if((await iw(this.currentLogFile)).size===0){if(await KX(this.currentLogFile,J,{flag:"w",mode:420}),(await iw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{HX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 bw(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 bw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return bw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(A$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return hX(16).toString("hex")}generateKey(){return hX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=hX(16),Y=ez("aes-256-gcm",w,A),f=o0.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:o0.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=hW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(o0.from(o0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(A$())return;let $=await iw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await IA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await iw(A).catch(()=>null))try{if(await zW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await CA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await KX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await iw(A).catch(()=>null))await zW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await IA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await CA(bw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=EW($),Y=w2(w),f=hW();await X2(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),GX(this.currentLogFile))try{let $=TW(this.currentLogFile,"r+");jW($),HX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!A$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await IA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await CA(bw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?l.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=y$.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${l.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!A$()){let B=fB[$],E=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:l.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:l.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
5
|
+
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:l.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!A$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let J=`${X} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
6
|
+
`;if(W)J+=`${W}
|
|
7
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!A$()){let A=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:l.blue("◐"),tag:A,message:`${l.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
8
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!A$()){let E=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:l.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!A$())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new rA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(A$())throw Error("createReadStream is not supported in browser environments");if(!GX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return EW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=o0.isBuffer($)?$:o0.from($,"base64"),f=Y.slice(0,16),X=Y.slice(-16),U=Y.slice(16,-16),W=$2("aes-256-gcm",A,f);return W.setAuthTag(X),o0.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return A$()}isServerMode(){return!A$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w);if(this.fancy&&!A$()){let X=$.split(`
|
|
9
|
+
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:l.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(W)})),B.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(J),showTimestamp:!1}))}else if(!A$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let f=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(A$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${l.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();y$.stdin.removeListener("data",A);try{if(typeof y$.stdin.setRawMode==="function")y$.stdin.setRawMode(!1)}catch{}y$.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof y$.stdin.setRawMode==="function")y$.stdin.setRawMode(!0)}catch{}y$.stdin.resume(),y$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!A$()){let U=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",W=l.blue("◐");console.error(`${W} ${U} ${l.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||A$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||A$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),W!==void 0)this.activeProgressBar.message=W;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||A$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||A$())return;y$.stdout.write(`${"\r".padEnd(y$.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||A$()||!y$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=l.green("━".repeat(Y)),U=l.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=w||A===100?l.green("✓"):l.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${l.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=y$.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,y$.stdout.write($.lastRenderedLine),w)y$.stdout.write(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||A$()||!y$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(A$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await IA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=bw(this.config.logDirectory,Y);if($.before)try{if((await iw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await CA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function bA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&u(w[0])&&"id"in w[0]&&w[0].id===3&&u(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(u(w)&&u($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(u($)&&"arr"in $&&Array.isArray($.arr)&&u(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&u(w[0])&&u($[0])){let Y=[...w];for(let f of $)if(u(f)&&"name"in f){if(!Y.find((U)=>u(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(u(f)&&"path"in f){if(!Y.find((U)=>u(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>aA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!u(w)||!u($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(u(f)&&u(A[Y]))A[Y]=bA(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&u(f[0])&&u(A[Y][0])){let X=[...f];for(let U of A[Y])if(u(U)&&"name"in U){if(!X.find((J)=>u(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(u(U)&&"path"in U){if(!X.find((J)=>u(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>aA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function rX($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:bA($,w);if(Array.isArray($))return A==="replace"?w:bA($,w);if(!u(w)||!u($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=bA(U,X);else if(u(X)&&u(U))Y[f]=rX(U,X,A);else Y[f]=X}return Y}function aA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aA($[A],w[A]))return!1;return!0}if(u($)&&u(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!aA($[f],w[f]))return!1}return!0}return!1}function u($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function ZA($,w,A="replace"){if(!lW($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return rX(w,f,A)}catch{return null}}catch{return null}}function m2($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((h)=>h.toUpperCase()).join("_")}`;if(A)I$.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let h=Z1.env[F]||Z1.env[H];if(h!==void 0){if(A)I$.info(`Using environment variable ${h?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(h);else if(typeof E==="boolean")J[B]=h.toLowerCase()==="true";else if(Array.isArray(E))try{let G=JSON.parse(h);if(Array.isArray(G))J[B]=G;else J[B]=h.split(",").map((K)=>K.trim())}catch{J[B]=h.split(",").map((G)=>G.trim())}else J[B]=h}}}return J}return X(f)}async function d2({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?m2($,f,X):f,B=A||Z1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)I$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],h=Array.from(new Set([B,k$(B,"config"),k$(B,".config"),Y?k$(B,Y):void 0].filter(Boolean)));for(let G of h){if(X)I$.info(`Searching for configuration in: ${G}`);let R=[k$(B,"config"),k$(B,".config")].concat(Y?[k$(B,Y)]:[]).includes(G)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let M of R)for(let N of E){let y=k$(G,`${M}${N}`),S=await ZA(y,J,W);if(S!==null){if(X)I$.success(`Configuration loaded from: ${y}`);return S}}}if($){let G=k$(zX(),".config",$),K=["config",`${$}.config`];if(w)K.push(`${w}.config`);if(X)I$.info(`Checking user config directory: ${G}`);for(let R of K)for(let M of E){let N=k$(G,`${R}${M}`),y=await ZA(N,J,W);if(y!==null){if(X)I$.success(`Configuration loaded from user config directory: ${N}`);return y}}}if($){let G=k$(zX(),".config"),K=[`.${$}.config`];if(w)K.push(`.${w}.config`);if(X)I$.info(`Checking user config directory for dotfile configs: ${G}`);for(let R of K)for(let M of E){let N=k$(G,`${R}${M}`),y=await ZA(N,J,W);if(y!==null){if(X)I$.success(`Configuration loaded from user config directory dotfile: ${N}`);return y}}}if($){let G=zX(),K=[`.${$}.config`,`.${$}`];if(w)K.push(`.${w}.config`),K.push(`.${w}`);if(X)I$.info(`Checking user home directory for dotfile configs: ${G}`);for(let R of K)for(let M of E){let N=k$(G,`${R}${M}`),y=await ZA(N,J,W);if(y!==null){if(X)I$.success(`Configuration loaded from user home directory: ${N}`);return y}}}try{let G=k$(B,"package.json");if(lW(G)){let K=await import(G),R=K[$];if(!R&&w){if(R=K[w],R&&X)I$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(X)I$.success(`Configuration loaded from package.json: ${R===K[$]?$:w}`);return rX(J,R,W)}catch(M){if(X)I$.warn("Failed to merge package.json config:",M)}}}catch(G){if(X)I$.warn("Failed to load package.json:",G)}if(X)I$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function l2($,w={}){let A=dA.cwd();while(A.includes("storage"))A=WW(A,"..");let Y=WW(A,$||"");if(w?.relative)return az(dA.cwd(),Y);return Y}async function g2(){try{let $=await d2({name:"clarity",alias:"logging",defaultConfig:nA,cwd:dA.cwd()});return{...nA,...$||{}}}catch{return nA}}function W$(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function t2(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof V0<"u"){let $=V0.type;if($==="renderer"||$==="worker")return!1;return!!(V0.versions&&(V0.versions.node||V0.versions.bun))}return!1}class rW{async format($){let w=await t2(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:vw.pid,hostname:w(),environment:vw.env.NODE_ENV||"development",platform:vw.platform,version:vw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vw.env.NODE_ENV||vw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...iX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new rW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...vA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...vA};return{...vA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!W$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await E2(this.config.logDirectory,RW.F_OK|RW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await j2(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:C0.from($);try{if(!SA(this.currentLogFile))await NX(this.currentLogFile,"",{mode:420});if(f=KW(this.currentLogFile,"a",420),B2(f,J,{flag:"a"}),GW(f),f!==void 0)qX(f),f=void 0;if((await uw(this.currentLogFile)).size===0){if(await NX(this.currentLogFile,J,{flag:"w",mode:420}),(await uw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{qX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return nw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return nw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return nw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return RX(16).toString("hex")}generateKey(){return RX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=RX(16),Y=U2("aes-256-gcm",w,A),f=C0.isBuffer($)?$:C0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=C0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=NW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(C0.from(C0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W$())return;if(!this.shouldWriteToFile())return;let $=await uw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await LA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await uw(A).catch(()=>null))try{if(await qW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await OA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await NX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await uw(A).catch(()=>null))await qW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await LA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await OA(nw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=HW($),Y=W2(w),f=NW();await z2(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),SA(this.currentLogFile))try{let $=KW(this.currentLogFile,"r+");GW($),qX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await LA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await OA(nw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?D.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||W$())return!1;let $=typeof O.env.NO_COLOR<"u",w=O.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof O.stderr<"u"&&O.stderr.isTTY||typeof O.stdout<"u"&&O.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=O.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${D.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=D.underline(D.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>D.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>D.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>D.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>D.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>D.strikethrough(Y)),w}supportsHyperlinks(){if(W$())return!1;let $=O.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=O.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(T2(w)||w.startsWith("./")||w.startsWith("../"))w=F2(w);else return null;return SA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":XB[$],T=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:D.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:D.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
13
|
+
`);for(let h of H)if(h.trim()&&!h.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:D.gray(` ${h}`),level:$,showTimestamp:!1}))}break}}else if(!W$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
14
14
|
`;if(W)E+=`${W}
|
|
15
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,
|
|
16
|
-
`);if(this[
|
|
17
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":D.green("✓"),tag:E,message:`${
|
|
18
|
-
`),
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
22
|
-
|
|
23
|
-
`;for(let
|
|
24
|
-
`,A+=` Type: ${
|
|
25
|
-
`,A+=` Description: ${
|
|
26
|
-
`,A+=` Example: ${
|
|
15
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!W$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!W$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!W$()&&O.stdout.isTTY)O.stdout.write(`
|
|
16
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!W$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":D.blue("◐"),tag:A,message:`${D.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
17
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":D.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!W$())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new sA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(W$())throw Error("createReadStream is not supported in browser environments");if(!SA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return HW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=C0.isBuffer($)?$:C0.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=J2("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=C0.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W$()}isServerMode(){return!W$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
18
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:D.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:D.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:D.cyan(E),showTimestamp:!1}))}else if(!W$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(W$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${D.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();O.stdin.removeListener("data",A);try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!1)}catch{}O.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof O.stdin.setRawMode==="function")O.stdin.setRawMode(!0)}catch{}O.stdin.resume(),O.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${D.blue("◐")} `;console.error(`${B}${J} ${D.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!O.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=D.green("━".repeat(Y)),U=D.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?D.green("✓"):D.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${D.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=O.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,O.stdout.write($.lastRenderedLine),w)O.stdout.write(`
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||W$()||!O.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(W$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await LA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=nw(this.config.logDirectory,Y);if($.before)try{if((await uw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await OA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function aW($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function sW($){return $ instanceof p$}function p2($){return $ instanceof oA}function r2($){if(sW($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class fY{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return i1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=VA.env[J]||(B?VA.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=VA.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof eA)throw j;throw e0.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw e0.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(VA.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
22
|
+
|
|
23
|
+
`;for(let Y of $)A+=`${Y.key}
|
|
24
|
+
`,A+=` Type: ${Y.type}
|
|
25
|
+
`,A+=` Description: ${Y.description}
|
|
26
|
+
`,A+=` Example: ${Y.example}
|
|
27
27
|
|
|
28
28
|
`;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
|
|
29
29
|
|
|
30
30
|
`;A+=`| Variable | Type | Description | Example |
|
|
31
31
|
`,A+=`|----------|------|-------------|----------|
|
|
32
|
-
`;for(let
|
|
33
|
-
`;return A}}function s9($,w){let A=NW("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function TW($,w,A={}){return GW($,w,A,new WeakMap)}function GW($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let W=f($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return hW($,w,U,J);if(!s$(w)||!s$($))return w;return wH($,w,A,J)}function hW($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return o9($,w);case"smart":return e9($,w,J);default:return w}return w}function o9($,w){let A=[...w];for(let J of $)if(!A.some((U)=>FY(U,J)))A.push(J);return A}function e9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(s$(w[0])&&s$($[0]))return $H($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function $H($,w,A){let J=[...w];for(let U of $){if(!s$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let W of Y)if(W in U){if(J.find((B)=>s$(B)&&(W in B)&&B[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function wH($,w,A,J){let U=w;if(s$(U)&&J.has(U))return J.get(U);let Y={...$};if(s$(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let W=U[f],Z=Y[f];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){Y[f]=W;continue}if(s$(W)&&s$(Z))Y[f]=GW(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=hW(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function LY($,w,A="replace"){return TW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function FY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!FY($[A],w[A]))return!1;return!0}if(s$($)&&s$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!FY($[U],w[U]))return!1}return!0}return!1}function s$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class nA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:W=!1}=A;if(U){let B=Pw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let Z=async()=>{if(!zA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),F=E.default||E,z="default"in E,j=Object.keys(E).length>0;if(!z&&!j)throw new y1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new y1($,Error("Configuration must export a valid object"),"unknown");let h={config:LY(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)Pw.setWithFileCheck("file",h,$,Y);return h}catch(B){throw B instanceof Error?t0.configLoad($,B):t0.configLoad($,Error(String(B)))}};if(f)return L1.track("loadFromPath",Z,{path:$});return Z()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(oU(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return zW(async()=>{return zA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!zA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=oU($,`${Y}${f}`);if(await this.checkFileAccess(W))J.push(W)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let W=oU($,f);if(await this.checkFileAccess(W))J.push(W)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!zA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class SY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,B=async()=>{let E=[],F=[],z={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,z);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],z);else return this.validateWithJSONSchema($,w,z)}catch(j){return E.push({path:"",message:`Validation failed: ${j}`,rule:"system"}),{isValid:!1,errors:E,warnings:F}}};if(W)return await L1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!G9(w))throw new C1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new C1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(f)){if(J.push({path:A,message:`Expected type ${W.join(" or ")}, got ${f}`,expected:W.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let W=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let W of w.required)if(!(W in f)){if(J.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[W,Z]of Object.entries(w.properties))if(W in f){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,B,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let Z of Object.keys(f))if(!W.has(Z))U.push({path:A?`${A}.${Z}`:Z,message:`Additional property '${Z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),W=this.validateWithRule(f,Y,Y.path);if(J.push(...W),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:yW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class VY{fileLoader=new nA;envProcessor=new vA;validator=new SY;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let Z=this.checkCache(f.name||"",f);if(Z)return Z}let W;try{W=await this.loadConfigurationStrategies(f,!0,A)}catch(Z){let B=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(B)throw Z;W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(Z instanceof Error&&Z.name==="ConfigLoadError"){let E=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),F=!E&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),z=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(B&&(z||E))throw Z;if(F&&(!B||!z))W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Z.message}`]};else throw Z}else W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Z instanceof Error?Z.message:String(Z)}`]}}if(U||Y)await this.validateConfiguration(W.config,U,Y,f.name);if(A?.enabled&&W)this.cacheResult(f.name||"",W,A,f);if(J?.enabled){let Z={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(Z);if(J.slowThreshold&&Z.duration>J.slowThreshold)Z0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw Z0.error(`Configuration loading failed after ${Z}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:W,checkEnv:Z=!0,arrayStrategy:B="replace",verbose:E=!1}=$,F=Y||Ew.cwd(),z=[],j=await this.loadLocalConfiguration(J,U,F,f,W,B,E,Z,A);if(j)return z.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(j,z,Z,J,E);let G=await this.loadHomeConfiguration(J,U,W,B,E,Z);if(G)return z.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(G,z,Z,J,E);let T=await this.loadPackageJsonConfiguration(J,U,F,W,B,E,Z);if(T)return z.push(D$(F,"package.json")),this.finalizeResult(T,z,Z,J,E);if(z.push(...this.getAllSearchPaths(J,U,F,f)),w)throw t0.configNotFound(J,z,U);return{...await this.applyEnvironmentVariables(J,W,Z,E),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let B=W?M1($,U,f):U,E=this.getLocalDirectories(A,J);for(let F of E){if(f)Z0.info(`Searching for configuration in: ${F}`);let z=this.fileLoader.generateConfigPaths($,F,w),j=await this.fileLoader.tryLoadFromPaths(z,B,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(j){if(f)Z0.success(`Configuration loaded from: ${j.source.path}`);return j}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?M1($,A,U):A,W=[D$(Lw(),".config",$),D$(Lw(),".config"),Lw()];for(let Z of W){if(U)Z0.info(`Checking home directory: ${Z}`);let B=this.fileLoader.generateConfigPaths($,Z,w),E=await this.fileLoader.tryLoadFromPaths(B,f,{arrayStrategy:J,verbose:U});if(E){if(U)Z0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?M1($,J,Y):J;try{let Z=D$(A,"package.json");if(!BY(Z))return null;let B=await import(Z),E=B[$],F=$;if(!E&&w)E=B[w],F=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(Y)Z0.success(`Configuration loaded from package.json: ${F}`);return{config:LY(W,E,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)Z0.warn("Failed to load package.json:",[Z instanceof Error?Z:Error(String(Z))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:M1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw t0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return Pw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);Pw.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,D$($,"config"),D$($,".config"),w?D$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(D$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[D$(Lw(),".config",$),D$(Lw(),".config"),Lw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function pZ($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function AH($){return S0.loadConfig({...$,__strictErrorHandling:!0})}async function qW($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await S0.loadConfig($);else J=await S0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)Z0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await S0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function JH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await S0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&pZ(A)))return(await S0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await S0.loadConfig({...$,cwd:$.cwd||Ew.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&pZ(w)))return(await S0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function UH($,w,A="replace"){let J=new nA;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function M1($,w,A=!1){let J=new vA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],j,G;for(let T of z)if(j=Ew.env[T],j!==void 0){G=T;break}if(j!==void 0&&G)if(typeof E==="boolean")Z[B]=["true","1","yes"].includes(j.toLowerCase());else if(typeof E==="number"){let T=Number(j);if(!Number.isNaN(T))Z[B]=T}else if(Array.isArray(E))try{Z[B]=JSON.parse(j)}catch{Z[B]=j.split(",").map((T)=>T.trim())}else Z[B]=j;else if(E&&typeof E==="object"&&!Array.isArray(E))Z[B]=Y(E,F)}return Z}return Y(w)}function YH($){let w=D$(Ew.cwd(),$.configDir),A=D$(Ew.cwd(),$.generatedDir),J=D$(A,"config-types.ts");if(!BY(yZ(J)))pz(yZ(J),{recursive:!0,mode:511});let U=BY(w)?tz(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${QH}
|
|
34
|
-
export type ConfigNames = ${
|
|
35
|
-
`;
|
|
36
|
-
${
|
|
32
|
+
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
33
|
+
`;return A}}function a2($,w){let A=AB("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function oW($,w,A={}){return eW($,w,A,new WeakMap)}function eW($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return $B($,w,f,Y);if(!$0(w)||!$0($))return w;return $h($,w,A,Y)}function $B($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return s2($,w);case"smart":return o2($,w,Y);default:return w}return w}function s2($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>xX(f,Y)))A.push(Y);return A}function o2($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return e2($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function e2($,w,A){let Y=[...w];for(let f of $){if(!$0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>$0(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function $h($,w,A,Y){let f=w;if($0(f)&&Y.has(f))return Y.get(f);let X={...$};if($0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if($0(W)&&$0(J))X[U]=eW(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=$B(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function aX($,w,A="replace"){return oW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function xX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!xX($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!xX($[f],w[f]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class XY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=gw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!QA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new x1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new x1($,Error("Configuration must export a valid object"),"unknown");let G={config:aX(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)gw.setWithFileCheck("file",G,$,X);return G}catch(B){throw B instanceof Error?e0.configLoad($,B):e0.configLoad($,Error(String(B)))}};if(U)return i1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(yX(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return aW(async()=>{return QA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!QA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=yX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=yX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!QA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class sX{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await i1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!h2(w))throw new P1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new P1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:JB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oX{fileLoader=new XY;envProcessor=new fY;validator=new sX;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)F0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw F0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Hw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let h=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(h)return T.push(Z$(j,"package.json")),this.finalizeResult(h,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw e0.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?k1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)F0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)F0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?k1($,A,f):A,W=[Z$(Pw(),".config",$),Z$(Pw(),".config"),Pw()];for(let J of W){if(f)F0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)F0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?k1($,Y,X):Y;try{let J=Z$(A,"package.json");if(!kX(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)F0.success(`Configuration loaded from package.json: ${j}`);return{config:aX(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)F0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:k1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw e0.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return gw.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);gw.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Z$($,"config"),Z$($,".config"),w?Z$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(Z$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[Z$(Pw(),".config",$),Z$(Pw(),".config"),Pw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function QW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function wh($){return _0.loadConfig({...$,__strictErrorHandling:!0})}async function wB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await _0.loadConfig($);else Y=await _0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)F0.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await _0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function Ah($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await _0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&QW(A)))return(await _0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await _0.loadConfig({...$,cwd:$.cwd||Hw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&QW(w)))return(await _0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function Yh($,w,A="replace"){let Y=new XY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function k1($,w,A=!1){let Y=new fY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((h)=>h.toUpperCase()).join("")}`,`${f}_${j.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let h of T)if(F=Hw.env[h],F!==void 0){H=h;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let h=Number(F);if(!Number.isNaN(h))J[B]=h}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((h)=>h.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function fh($){let w=Z$(Hw.cwd(),$.configDir),A=Z$(Hw.cwd(),$.generatedDir),Y=Z$(A,"config-types.ts");if(!kX(JW(Y)))gz(JW(Y),{recursive:!0,mode:511});let f=kX(w)?tz(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${kh}
|
|
34
|
+
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
35
|
+
`;pz(Y,X,{mode:438})}function Xh($){let w=null,A=null,Y=()=>{if(!A)A=wB($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)F0.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function Uh($){let w=yW(K2.cwd(),$?.configDir||"./config");function A(){if(!H2(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=G2(w).filter((J)=>f.has(MX(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=MX(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=MX(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((B)=>B.base),U=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=f.length?`{
|
|
36
|
+
${f.map((B)=>{let E=yW(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${E}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
38
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
39
39
|
export type ConfigByName = ${W}
|
|
40
40
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
41
41
|
export type ConfigOf = Config
|
|
42
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function PH($,w={}){let A=XA.cwd();while(A.includes("storage"))A=uZ(A,"..");let J=uZ(A,$||"");if(w?.relative)return R9(XA.cwd(),J);return J}function W$(){if(L0.env.NODE_ENV==="test"||L0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function iH(){if(L0.env.NODE_ENV==="test"||L0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof L0<"u"){let $=L0.type;if($==="renderer"||$==="worker")return!1;return!!(L0.versions&&(L0.versions.node||L0.versions.bun))}return!1}class VW{async format($){let w=await iH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:xw.pid,hostname:w(),environment:xw.env.NODE_ENV||"development",platform:xw.platform,version:xw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xw.env.NODE_ENV||xw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...bA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new VW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...ZY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZY};return{...ZY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:bA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!W$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await L9(this.config.logDirectory,dZ.F_OK|dZ.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await S9(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:M0.from($);try{if(!HA(this.currentLogFile))await AY(this.currentLogFile,"",{mode:420});if(U=mZ(this.currentLogFile,"a",420),C9(U,Z,{flag:"a"}),nZ(U),U!==void 0)wY(U),U=void 0;if((await kw(this.currentLogFile)).size===0){if(await AY(this.currentLogFile,Z,{flag:"w",mode:420}),(await kw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<f-1){let F=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let z=W*2**Y;await new Promise((j)=>setTimeout(j,z)),Y++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{wY(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Z){if(Y===f-1){let E=Z,F=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),Z}Y++;let B=W*2**(Y-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,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 Qw(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 Qw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Qw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Z])=>Z.createdAt.getTime()-W.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[W]of U.slice(f))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return $Y(16).toString("hex")}generateKey(){return $Y(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=$Y(16),J=M9("aes-256-gcm",w,A),U=M0.isBuffer($)?$:M0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),B=M0.allocUnsafe(16+W+16);return A.copy(B,0),Y.copy(B,16),f.copy(B,16+Y.length),Z.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let J=lZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(M0.from(M0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W$())return;if(!this.shouldWriteToFile())return;let $=await kw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await TA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await kw(A).catch(()=>null))try{if(await gZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await GA(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await AY(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await kw(A).catch(()=>null))await gZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await TA(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await GA(Qw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=vZ($),J=y9(w),U=lZ();await X9(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),HA(this.currentLogFile))try{let $=mZ(this.currentLogFile,"r+");nZ($),wY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await TA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await GA(Qw(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||W$())return!1;let $=typeof O.env.NO_COLOR<"u",w=O.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof O.stderr<"u"&&O.stderr.isTTY||typeof O.stdout<"u"&&O.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=O.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${P.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=P.underline(P.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>P.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>P.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>P.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>P.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>P.strikethrough(J)),w}supportsHyperlinks(){if(W$())return!1;let $=O.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=O.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(V9(w)||w.startsWith("./")||w.startsWith("../"))w=O9(w);else return null;return HA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);let{consoleText:Z,fileText:B}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":mH[$],z=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:P.gray(Z),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:P.green(Z),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.error(j),W){let G=W.split(`
|
|
43
|
-
`);for(let
|
|
42
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function xh($,w={}){let A=tA.cwd();while(A.includes("storage"))A=MW(A,"..");let Y=MW(A,$||"");if(w?.relative)return q2(tA.cwd(),Y);return Y}function E$(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ih(){if(Q0.env.NODE_ENV==="test"||Q0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Q0<"u"){let $=Q0.type;if($==="renderer"||$==="worker")return!1;return!!(Q0.versions&&(Q0.versions.node||Q0.versions.bun))}return!1}class jB{async format($){let w=await ih(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class UY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...$Y},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new jB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{..._X,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{..._X};return{..._X,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:$Y.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!E$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await C2(this.config.logDirectory,LW.F_OK|LW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await S2(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:S0.from($);try{if(!_A(this.currentLogFile))await SX(this.currentLogFile,"",{mode:420});if(f=SW(this.currentLogFile,"a",420),I2(f,J,{flag:"a"}),CW(f),f!==void 0)CX(f),f=void 0;if((await mw(this.currentLogFile)).size===0){if(await SX(this.currentLogFile,J,{flag:"w",mode:420}),(await mw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{CX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 dw(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 dw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return dw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return IX(16).toString("hex")}generateKey(){return IX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=IX(16),Y=N2("aes-256-gcm",w,A),f=S0.isBuffer($)?$:S0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=S0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=VW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(S0.from(S0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E$())return;if(!this.shouldWriteToFile())return;let $=await mw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await DA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await mw(A).catch(()=>null))try{if(await OW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await kA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await SX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await mw(A).catch(()=>null))await OW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await DA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await kA(dw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=IW($),Y=M2(w),f=VW();await V2(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),_A(this.currentLogFile))try{let $=SW(this.currentLogFile,"r+");CW($),CX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await DA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await kA(dw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E$())return!1;let $=typeof V.env.NO_COLOR<"u",w=V.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof V.stderr<"u"&&V.stderr.isTTY||typeof V.stdout<"u"&&V.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=V.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${P.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=P.underline(P.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>P.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>P.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>P.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>P.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>P.strikethrough(Y)),w}supportsHyperlinks(){if(E$())return!1;let $=V.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=V.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(L2(w)||w.startsWith("./")||w.startsWith("../"))w=O2(w);else return null;return _A(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":vh[$],T=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:P.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:P.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
43
|
+
`);for(let h of H)if(h.trim()&&!h.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:P.gray(` ${h}`),level:$,showTimestamp:!1}))}break}}else if(!E$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
44
44
|
`;if(W)E+=`${W}
|
|
45
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,
|
|
46
|
-
`);if(this[
|
|
47
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:E,message:`${
|
|
48
|
-
`),
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
52
|
-
|
|
53
|
-
`;for(let
|
|
54
|
-
`,A+=` Type: ${
|
|
55
|
-
`,A+=` Description: ${
|
|
56
|
-
`,A+=` Example: ${
|
|
45
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!E$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!E$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!E$()&&V.stdout.isTTY)V.stdout.write(`
|
|
46
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!E$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:A,message:`${P.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
47
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!E$())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new UY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(E$())throw Error("createReadStream is not supported in browser environments");if(!_A(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return IW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=S0.isBuffer($)?$:S0.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=y2("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=S0.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E$()}isServerMode(){return!E$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
48
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(E),showTimestamp:!1}))}else if(!E$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(E$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();V.stdin.removeListener("data",A);try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!1)}catch{}V.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof V.stdin.setRawMode==="function")V.stdin.setRawMode(!0)}catch{}V.stdin.resume(),V.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${B}${J} ${P.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!V.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=P.green("━".repeat(Y)),U=P.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=V.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,V.stdout.write($.lastRenderedLine),w)V.stdout.write(`
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E$()||!V.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(E$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await DA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=dw(this.config.logDirectory,Y);if($.before)try{if((await mw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await kA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function mh($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class $8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return lX.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=xA.env[J]||(B?xA.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=xA.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof eX)throw j;throw tw.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw tw.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(xA.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
52
|
+
|
|
53
|
+
`;for(let Y of $)A+=`${Y.key}
|
|
54
|
+
`,A+=` Type: ${Y.type}
|
|
55
|
+
`,A+=` Description: ${Y.description}
|
|
56
|
+
`,A+=` Example: ${Y.example}
|
|
57
57
|
|
|
58
58
|
`;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
|
|
59
59
|
|
|
60
60
|
`;A+=`| Variable | Type | Description | Example |
|
|
61
61
|
`,A+=`|----------|------|-------------|----------|
|
|
62
|
-
`;for(let
|
|
63
|
-
`;return A}}function gH($,w,A={}){return PW($,w,A,new WeakMap)}function PW($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let W=f($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return bW($,w,U,J);if(!o$(w)||!o$($))return w;return rH($,w,A,J)}function bW($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return lH($,w);case"smart":return pH($,w,J);default:return w}return w}function lH($,w){let A=[...w];for(let J of $)if(!A.some((U)=>KY(U,J)))A.push(J);return A}function pH($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return tH($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function tH($,w,A){let J=[...w];for(let U of $){if(!o$(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let W of Y)if(W in U){if(J.find((B)=>o$(B)&&(W in B)&&B[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function rH($,w,A,J){let U=w;if(o$(U)&&J.has(U))return J.get(U);let Y={...$};if(o$(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let W=U[f],Z=Y[f];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){Y[f]=W;continue}if(o$(W)&&o$(Z))Y[f]=PW(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=bW(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function iW($,w,A="replace"){return gH($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function KY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!KY($[A],w[A]))return!1;return!0}if(o$($)&&o$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!KY($[U],w[U]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class cW{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:W=!1}=A;if(U){let B=LA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let Z=async()=>{if(!NA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),F=E.default||E,z="default"in E,j=Object.keys(E).length>0;if(!z&&!j)throw new iA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new iA($,Error("Configuration must export a valid object"),"unknown");let h={config:iW(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)LA.setWithFileCheck("file",h,$,Y);return h}catch(B){throw B instanceof Error?bw.configLoad($,B):bw.configLoad($,Error(String(B)))}};if(f)return RY.track("loadFromPath",Z,{path:$});return Z()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(WY(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let Y of J){if(!Y)continue;if(A.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)A.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let U=new Set;return A.filter((Y)=>{if(!Y||U.has(Y))return!1;return U.add(Y),!0})}checkFileAccess($){return dH(async()=>{return NA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!NA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=WY($,`${Y}${f}`);if(await this.checkFileAccess(W))J.push(W)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let W=WY($,f);if(await this.checkFileAccess(W))J.push(W)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!NA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class uW{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,B=async()=>{let E=[],F=[],z={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,z);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],z);else return this.validateWithJSONSchema($,w,z)}catch(j){return E.push({path:"",message:`Validation failed: ${j}`,rule:"system"}),{isValid:!1,errors:E,warnings:F}}};if(W)return await RY.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!aH(w))throw new cA(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new cA(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(f)){if(J.push({path:A,message:`Expected type ${W.join(" or ")}, got ${f}`,expected:W.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let W=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let W of w.required)if(!(W in f)){if(J.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[W,Z]of Object.entries(w.properties))if(W in f){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,B,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let Z of Object.keys(f))if(!W.has(Z))U.push({path:A?`${A}.${Z}`:Z,message:`Additional property '${Z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),W=this.validateWithRule(f,Y,Y.path);if(J.push(...W),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:sH},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function oH($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class vW{fileLoader=new cW;envProcessor=new XY;validator=new uW;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let Z=this.checkCache(f.name||"",f);if(Z)return Z}let W;try{W=await this.loadConfigurationStrategies(f,!0,A)}catch(Z){let B=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(B)throw Z;W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(Z instanceof Error&&Z.name==="ConfigLoadError"){let E=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),F=!E&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),z=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(B&&(z||E))throw Z;if(F&&(!B||!z))W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Z.message}`]};else throw Z}else W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Z instanceof Error?Z.message:String(Z)}`]}}if(U||Y)await this.validateConfiguration(W.config,U,Y,f.name);if(A?.enabled&&W)this.cacheResult(f.name||"",W,A,f);if(J?.enabled){let Z={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(Z);if(J.slowThreshold&&Z.duration>J.slowThreshold)I0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let Z=Date.now()-w;throw I0.error(`Configuration loading failed after ${Z}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:W,checkEnv:Z=!0,arrayStrategy:B="replace",verbose:E=!1}=$,F=Y||uA.cwd(),z=[],j=await this.loadLocalConfiguration(J,U,F,f,W,B,E,Z,A);if(j)return z.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(j,z,Z,J,E);let G=await this.loadHomeConfiguration(J,U,W,B,E,Z);if(G)return z.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(G,z,Z,J,E);let T=await this.loadPackageJsonConfiguration(J,U,F,W,B,E,Z);if(T)return z.push(a$(F,"package.json")),this.finalizeResult(T,z,Z,J,E);if(z.push(...this.getAllSearchPaths(J,U,F,f)),w)throw bw.configNotFound(J,z,U);return{...await this.applyEnvironmentVariables(J,W,Z,E),warnings:[`No configuration file found for "${J}"${oH(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let B=W?KA($,U,f):U,E=this.getLocalDirectories(A,J);for(let F of E){if(f)I0.info(`Searching for configuration in: ${F}`);let z=this.fileLoader.generateConfigPaths($,F,w),j=await this.fileLoader.tryLoadFromPaths(z,B,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(j){if(f)I0.success(`Configuration loaded from: ${j.source.path}`);return j}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?KA($,A,U):A,W=[a$(Cw(),".config",$),a$(Cw(),".config"),Cw()];for(let Z of W){if(U)I0.info(`Checking home directory: ${Z}`);let B=this.fileLoader.generateConfigPaths($,Z,w),E=await this.fileLoader.tryLoadFromPaths(B,f,{arrayStrategy:J,verbose:U});if(E){if(U)I0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?KA($,J,Y):J;try{let Z=a$(A,"package.json");if(!gz(Z))return null;let B={};try{B=JSON.parse(lz(Z,"utf8"))}catch(z){if(Y)I0.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let E=B[$],F=$;if(!E&&w){let z=Array.isArray(w)?w:[w];for(let j of z){if(!j)continue;if(B[j]){E=B[j],F=j;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(Y)I0.success(`Configuration loaded from package.json: ${F}`);return{config:iW(W,E,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)I0.warn("Failed to load package.json:",[Z instanceof Error?Z:Error(String(Z))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:KA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw bw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return LA.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);LA.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,a$($,"config"),a$($,".config"),w?a$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(a$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[a$(Cw(),".config",$),a$(Cw(),".config"),Cw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function KA($,w,A=!1){let J=new XY,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],j,G;for(let T of z)if(j=uA.env[T],j!==void 0){G=T;break}if(j!==void 0&&G)if(typeof E==="boolean")Z[B]=["true","1","yes"].includes(j.toLowerCase());else if(typeof E==="number"){let T=Number(j);if(!Number.isNaN(T))Z[B]=T}else if(Array.isArray(E))try{Z[B]=JSON.parse(j)}catch{Z[B]=j.split(",").map((T)=>T.trim())}else Z[B]=j;else if(E&&typeof E==="object"&&!Array.isArray(E))Z[B]=Y(E,F)}return Z}return Y(w)}var LA,RY,_9,D9=($)=>$,Q9=($,w)=>{for(var A in w)_9($,A,{get:w[A],enumerable:!0,configurable:!0,set:k9.bind(w,A)})},x9=($,w)=>()=>($&&(w=$($=0)),w),EW,NW,Pw,L1,KW,WH,BH,tZ,MA,jY,K$,g,EH,rZ,FH,aZ,jH,zH,JY,HH,sZ,oZ,UY,TH,GH,hH,qH,IA,RW,NH,R$,KH,RH,eZ,yA,zY,Z$,D,MH,$W,IH,wW,yH,CH,YY,LH,AW,JW,SH,fY,VH,OH,XH,_H,DH,CA,MW,kH,QH="0.15.6",g$,xA,y1,HY,TY,PA,GY,hY,C1,qY,NY,t0,IW,yW,Z0,S0,CW,LW,xH,bH,SW,bA,UN,G$,P,YN,cH,fN,uH,ZN,WN,UW,BN,vH,nH,EN,YW,FN,jN,zN,HN,TN,ZY,mH,GN,W0,OW,iA,XW,_W,OY,DW,kW,cA,QW,xW,bw,sH,I0,RN,MN,IN;var _Y=X$(()=>{LA=new fW,RY=new ZW,_9=Object.defineProperty;EW={};Q9(EW,{withErrorRecovery:()=>zW,tryLoadConfig:()=>UH,loadConfigWithResult:()=>AH,loadConfig:()=>qW,isRetryableError:()=>a9,isConfigNotFoundError:()=>r9,isBunfigError:()=>HW,globalPerformanceMonitor:()=>L1,globalCache:()=>Pw,getEnvOrDefault:()=>s9,generateConfigTypes:()=>YH,defaultGeneratedDir:()=>LW,defaultConfigDir:()=>CW,deepMergeWithArrayStrategy:()=>LY,deepMerge:()=>TW,createLibraryConfig:()=>fH,config:()=>JH,bunfigPlugin:()=>ZH,applyEnvVarsToConfig:()=>M1,TypeGenerationError:()=>hY,SchemaValidationError:()=>C1,PluginError:()=>NY,PerformanceMonitor:()=>IY,FileSystemError:()=>GY,ErrorFactory:()=>t0,EnvVarError:()=>PA,EnvProcessor:()=>vA,ConfigValidator:()=>SY,ConfigValidationError:()=>HY,ConfigNotFoundError:()=>xA,ConfigMergeError:()=>TY,ConfigLoader:()=>VY,ConfigLoadError:()=>y1,ConfigFileLoader:()=>nA,ConfigCache:()=>MY,CacheUtils:()=>KW,BunfigError:()=>g$,BrowserConfigError:()=>qY,ArrayMergeStrategies:()=>IW});xH=x9(async()=>{NW=import.meta.require,Pw=new MY,L1=new IY,KW={createKey:P9,isEquivalent:b9,estimateMemoryUsage:i9},WH=OA(EY.cwd(),"config"),BH=OA(EY.cwd(),"src/generated"),tZ=VA.env.CLARITY_LOG_DIR||oz(v9(),"logs"),MA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},jY=await n9(),K$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},g=K$,EH=K$.red,rZ=K$.green,FH=K$.yellow,aZ=K$.blue,jH=K$.magenta,zH=K$.cyan,JY=K$.white,HH=K$.gray,sZ=K$.bgRed,oZ=K$.bgYellow,UY=K$.bold,TH=K$.dim,GH=K$.italic,hH=K$.underline,qH=K$.reset,IA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RW={debug:"\uD83D\uDD0D",info:aZ("ℹ"),success:rZ("✓"),warning:oZ(JY(UY(" WARN "))),error:sZ(JY(UY(" ERROR ")))},NH=new DA("stacks"),R$=new DA("bunfig",{showTags:!0}),KH=_$(I1.cwd(),"config"),RH=_$(I1.cwd(),"src/generated"),eZ=SA.env.CLARITY_LOG_DIR||az(l9(),"logs"),yA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},zY=await p9(),Z$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},D=Z$,MH=Z$.red,$W=Z$.green,IH=Z$.yellow,wW=Z$.blue,yH=Z$.magenta,CH=Z$.cyan,YY=Z$.white,LH=Z$.gray,AW=Z$.bgRed,JW=Z$.bgYellow,SH=Z$.bgGray,fY=Z$.bold,VH=Z$.dim,OH=Z$.italic,XH=Z$.underline,_H=Z$.strikethrough,DH=Z$.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},MW={debug:"\uD83D\uDD0D",info:wW("ℹ"),success:$W("✓"),warning:JW(YY(fY(" WARN "))),error:AW(YY(fY(" ERROR ")))},kH=new QA("stacks"),g$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},xA=class extends g${code="CONFIG_NOT_FOUND";constructor(w,A,J){let U=J?` or alias "${J}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},y1=class extends g${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},HY=class extends g${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},TY=class extends g${code="CONFIG_MERGE_ERROR";constructor(w,A,J,U){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:U,originalError:J.name,originalMessage:J.message});this.cause=J}},PA=class extends g${code="ENV_VAR_ERROR";constructor(w,A,J,U){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:U})}},GY=class extends g${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},hY=class extends g${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},C1=class extends g${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},qY=class extends g${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,U){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:U})}},NY=class extends g${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},t0={configNotFound($,w,A){return new xA($,w,A)},configLoad($,w,A){return new y1($,w,A)},configValidation($,w,A){return new HY($,w,A)},configMerge($,w,A,J){return new TY($,w,A,J)},envVar($,w,A,J){return new PA($,w,A,J)},fileSystem($,w,A){return new GY($,w,A)},typeGeneration($,w,A){return new hY($,w,A)},schemaValidation($,w,A){return new C1($,w,A)},browserConfig($,w,A,J){return new qY($,w,A,J)},plugin($,w,A){return new NY($,w,A)}},IW={replace:"replace",concat:"concat",smart:"smart"},yW=/^https?:\/\//,Z0=new QA("bunfig",{showTags:!0}),S0=new VY,CW=D$(Ew.cwd(),"config"),LW=D$(Ew.cwd(),"src/generated")});bH=XA.env.CLARITY_LOG_DIR||K9(PH(),"logs"),SW={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bA={...SW},UN=(async()=>{try{let{loadConfig:$}=await xH().then(()=>EW),w=await $({name:"clarity",alias:"logging",defaultConfig:SW,cwd:XA.cwd()});if(w)Object.assign(bA,w)}catch{}return bA})();G$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=G$,YN=G$.red,cH=G$.green,fN=G$.yellow,uH=G$.blue,ZN=G$.magenta,WN=G$.cyan,UW=G$.white,BN=G$.gray,vH=G$.bgRed,nH=G$.bgYellow,EN=G$.bgGray,YW=G$.bold,FN=G$.dim,jN=G$.italic,zN=G$.underline,HN=G$.strikethrough,TN=G$.reset,ZY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mH={debug:"\uD83D\uDD0D",info:uH("ℹ"),success:cH("✓"),warning:nH(UW(YW(" WARN "))),error:vH(UW(YW(" ERROR ")))};GN=new mA("stacks");W0=class W0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};OW=class OW extends W0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],U="";if(J.length===1)U=` or alias "${J[0]}"`;else if(J.length>1)U=` or aliases ${J.map((Y)=>`"${Y}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};iA=class iA extends W0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};XW=class XW extends W0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};_W=class _W extends W0{code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}};OY=class OY extends W0{code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}};DW=class DW extends W0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};kW=class kW extends W0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};cA=class cA extends W0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};QW=class QW extends W0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}};xW=class xW extends W0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};bw={configNotFound($,w,A){return new OW($,w,A)},configLoad($,w,A){return new iA($,w,A)},configValidation($,w,A){return new XW($,w,A)},configMerge($,w,A,J){return new _W($,w,A,J)},envVar($,w,A,J){return new OY($,w,A,J)},fileSystem($,w,A){return new DW($,w,A)},typeGeneration($,w,A){return new kW($,w,A)},schemaValidation($,w,A){return new cA($,w,A)},browserConfig($,w,A,J){return new QW($,w,A,J)},plugin($,w,A){return new xW($,w,A)}};sH=/^https?:\/\//;I0=new mA("bunfig",{showTags:!0});RN=new vW;MN=a$(uA.cwd(),"config"),IN=a$(uA.cwd(),"src/generated")});var K;var r0=X$(()=>{K={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as wT}from"node:module";import QY from"node:os";import xY from"node:path";import{existsSync as nW,statSync as mW}from"fs";import{existsSync as AT,mkdirSync as bN,readdirSync as iN,readFileSync as JT,writeFileSync as cN}from"fs";import{homedir as cw}from"os";import{dirname as nN,resolve as e$}from"path";import CJ from"process";import{existsSync as dW,statSync as gW}from"fs";import{existsSync as w8,mkdirSync as UT,readdirSync as YT,writeFileSync as fT}from"fs";import{homedir as uw}from"os";import{dirname as lW,resolve as Q$}from"path";import Fw from"process";import{join as ZT,relative as WT,resolve as pW}from"path";import BJ from"process";import{existsSync as QB,mkdirSync as oN,readdirSync as eN,writeFileSync as $K}from"fs";import{homedir as PY}from"os";import{dirname as JK,resolve as k$}from"path";import X1 from"process";import{join as BT,relative as ET,resolve as tW}from"path";import EJ from"process";import{existsSync as xB,mkdirSync as WK,readdirSync as BK,writeFileSync as EK}from"fs";import{dirname as jK,resolve as FJ}from"path";import A8 from"process";import{Buffer as a0}from"buffer";import{createCipheriv as FT,createDecipheriv as jT,randomBytes as bY}from"crypto";import{closeSync as iY,createReadStream as rW,createWriteStream as zT,existsSync as cY,fsyncSync as aW,openSync as sW,writeFileSync as HT}from"fs";import{access as TT,constants as oW,mkdir as GT,readdir as dA,rename as eW,stat as vw,unlink as gA,writeFile as uY}from"fs/promises";import{join as nw}from"path";import M$ from"process";import{pipeline as hT}from"stream/promises";import{createGzip as $B}from"zlib";import mw from"process";import _0 from"process";import{Buffer as V0}from"buffer";import{createCipheriv as qT,createDecipheriv as NT,randomBytes as vY}from"crypto";import{closeSync as nY,createReadStream as wB,createWriteStream as KT,existsSync as lA,fsyncSync as AB,openSync as JB,writeFileSync as RT}from"fs";import{access as MT,constants as UB,mkdir as IT,readdir as pA,rename as YB,stat as dw,unlink as tA,writeFile as mY}from"fs/promises";import{isAbsolute as yT,join as gw,resolve as CT}from"path";import v from"process";import{pipeline as LT}from"stream/promises";import{createGzip as fB}from"zlib";import lw from"process";import D0 from"process";import rA from"process";import{existsSync as aA}from"fs";import{resolve as dY}from"path";import{existsSync as ST}from"fs";import{existsSync as VT,readdirSync as OT}from"fs";import{extname as gY,resolve as ZB}from"path";import XT from"process";import{join as _T,relative as DT,resolve as WB}from"path";import jJ from"process";import{Buffer as O0}from"buffer";import{createCipheriv as kT,createDecipheriv as QT,randomBytes as lY}from"crypto";import{closeSync as pY,createReadStream as BB,createWriteStream as xT,existsSync as sA,fsyncSync as EB,openSync as FB,writeFileSync as PT}from"fs";import{access as bT,constants as jB,mkdir as iT,readdir as oA,rename as zB,stat as pw,unlink as eA,writeFile as tY}from"fs/promises";import{isAbsolute as cT,join as tw,resolve as uT}from"path";import n from"process";import{pipeline as vT}from"stream/promises";import{createGzip as HB}from"zlib";import rw from"process";import k0 from"process";import $J from"process";import{existsSync as wJ}from"fs";import{resolve as rY}from"path";import{existsSync as nT}from"fs";import{exec as E2}from"node:child_process";import VB from"node:fs";import F2 from"node:os";import B0 from"node:path";import hE from"node:process";import{promisify as j2}from"node:util";import ew from"node:crypto";import Q0 from"node:fs";import T8 from"node:path";import{execSync as kB}from"node:child_process";import yJ from"node:os";class PB{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!nW($))return!0;return mW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=nW(A)?mW(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class bB{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function gT($,w){this[$]=dT.bind(null,w)}class h8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!dW($))return!0;return gW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=dW(A)?gW(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class q8{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function tT($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function rT($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function aT($){return $.getStats().size*2}function N8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&a(w[0])&&"id"in w[0]&&w[0].id===3&&a(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(a(w)&&a($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(a($)&&"arr"in $&&Array.isArray($.arr)&&a(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&a(w[0])&&a($[0])){let J=[...w];for(let U of $)if(a(U)&&"name"in U){if(!J.find((Y)=>a(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(a(U)&&"path"in U){if(!J.find((Y)=>a(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>HJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!a(w)||!a($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(a(U)&&a(A[J]))A[J]=N8(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&a(U[0])&&a(A[J][0])){let Y=[...U];for(let f of A[J])if(a(f)&&"name"in f){if(!Y.find((W)=>a(W)&&("name"in W)&&W.name===f.name))Y.push(f)}else if(a(f)&&"path"in f){if(!Y.find((W)=>a(W)&&("path"in W)&&W.path===f.path))Y.push(f)}else if(!Y.some((W)=>HJ(W,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function HJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!HJ($[A],w[A]))return!1;return!0}if(a($)&&a(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!HJ($[U],w[U]))return!1}return!0}return!1}function a($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function sT($,w){if(!xB($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return N8(w,J)}catch{return null}}catch{return null}}async function oT({name:$="",cwd:w,defaultConfig:A}){let J=w||A8.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=FJ(J,`${f}${W}`),B=await sT(Z,A);if(B!==null)return B}try{let f=FJ(J,"package.json");if(xB(f)){let W=(await import(f))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return N8(A,W)}catch{}}}catch{}return A}function eT($,w={}){let A=EJ.cwd();while(A.includes("storage"))A=tW(A,"..");let J=tW(A,$||"");if(w?.relative)return ET(EJ.cwd(),J);return J}async function $G(){try{let $=await oT({name:"clarity",defaultConfig:YJ,cwd:EJ.cwd(),endpoint:"",headers:{}});return{...YJ,...$}}catch{return YJ}}function w$(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wG(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof _0<"u"){let $=_0.type;if($==="renderer"||$==="worker")return!1;return!!(_0.versions&&(_0.versions.node||_0.versions.bun))}return!1}class cB{async format($){let w=await wG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:mw.pid,hostname:w(),environment:mw.env.NODE_ENV||"development",platform:mw.platform,version:mw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mw.env.NODE_ENV||mw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class TJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...U8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new cB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??M$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...fJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...fJ};return{...fJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:U8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,f=1000;while(U<Y)try{try{try{await TT(this.config.logDirectory,oW.F_OK|oW.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await GT(this.config.logDirectory,{recursive:!0,mode:493});else if(Z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Z;else throw Z}}catch(Z){throw console.error("Debug: [writeToFile] Failed to create log directory:",Z),Z}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:a0.from($);try{if(!cY(this.currentLogFile))await uY(this.currentLogFile,"",{mode:420});if(J=sW(this.currentLogFile,"a",420),HT(J,W,{flag:"a"}),aW(J),J!==void 0)iY(J),J=void 0;if((await vw(this.currentLogFile)).size===0){if(await uY(this.currentLogFile,W,{flag:"w",mode:420}),(await vw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let B=Z;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<Y-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,E);let F=f*2**U;await new Promise((z)=>setTimeout(z,F)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(J!==void 0)try{iY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}U++;let Z=f*2**(U-1);await new Promise((B)=>setTimeout(B,Z))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}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 nw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return nw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return nw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(w$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,f],[,W])=>W.createdAt.getTime()-f.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[f]of J.slice(Y))this.encryptionKeys.delete(f),this.keys.delete(f)}generateKeyId(){return bY(16).toString("hex")}generateKey(){return bY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=bY(16),J=FT("aes-256-gcm",w,A),U=a0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:a0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=$B(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(a0.from(a0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(w$())return;let $=await vw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await dA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await vw(A).catch(()=>null))try{if(await eW(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await gA(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await uY(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await vw(A).catch(()=>null))await eW(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await dA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await gA(nw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=rW($),J=zT(w),U=$B();await hT(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),cY(this.currentLogFile))try{let $=sW(this.currentLogFile,"r+");aW($),iY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!w$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await dA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await gA(nw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?l.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=M$.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${l.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);if(this.fancy&&!w$()){let B=rB[$],E=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:l.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:l.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.error(F),W){let z=W.split(`
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`,Z=Z.replace(this.ANSI_PATTERN,""),this.fancy&&!w$()){let B=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:l.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!w$())console.error(Z.trim());await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new TJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(w$())throw Error("createReadStream is not supported in browser environments");if(!cY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=a0.isBuffer($)?$:a0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W=jT("aes-256-gcm",A,U);return W.setAuthTag(Y),a0.concat([W.update(f),W.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return w$()}isServerMode(){return!w$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!w$()){let Y=$.split(`
|
|
68
|
-
`)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||w$()||!M$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(w$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await dA(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=nw(this.config.logDirectory,J);if($.before)try{if((await vw(U)).mtime>=$.before)continue}catch(Y){console.error(`Failed to get stats for file ${U}:`,Y);continue}A.push(U)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await gA(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function UJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&m(w[0])&&"id"in w[0]&&w[0].id===3&&m(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(m(w)&&m($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(m($)&&"arr"in $&&Array.isArray($.arr)&&m(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&m(w[0])&&m($[0])){let J=[...w];for(let U of $)if(m(U)&&"name"in U){if(!J.find((Y)=>m(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(m(U)&&"path"in U){if(!J.find((Y)=>m(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>GJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!m(w)||!m($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(m(U)&&m(A[J]))A[J]=UJ(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&m(U[0])&&m(A[J][0])){let Y=[...U];for(let f of A[J])if(m(f)&&"name"in f){if(!Y.find((W)=>m(W)&&("name"in W)&&W.name===f.name))Y.push(f)}else if(m(f)&&"path"in f){if(!Y.find((W)=>m(W)&&("path"in W)&&W.path===f.path))Y.push(f)}else if(!Y.some((W)=>GJ(W,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function K8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:UJ($,w);if(Array.isArray($))return A==="replace"?w:UJ($,w);if(!m(w)||!m($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],f=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(f))if(A==="replace")J[U]=Y;else J[U]=UJ(f,Y);else if(m(Y)&&m(f))J[U]=K8(f,Y,A);else J[U]=Y}return J}function GJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!GJ($[A],w[A]))return!1;return!0}if(m($)&&m(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!GJ($[U],w[U]))return!1}return!0}return!1}function m($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AJ($,w,A="replace"){if(!QB($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return K8(w,U,A)}catch{return null}}catch{return null}}function AG($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),j=`${J}_${F.map(z).join("_")}`,G=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)y$.info(`Checking environment variable ${j} for config ${$}.${F.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))Z[B]=Y(E,F);else{let T=X1.env[j]||X1.env[G];if(T!==void 0){if(A)y$.info(`Using environment variable ${T?j:G} for config ${$}.${F.join(".")}`);if(typeof E==="number")Z[B]=Number(T);else if(typeof E==="boolean")Z[B]=T.toLowerCase()==="true";else if(Array.isArray(E))try{let h=JSON.parse(T);if(Array.isArray(h))Z[B]=h;else Z[B]=T.split(",").map((q)=>q.trim())}catch{Z[B]=T.split(",").map((h)=>h.trim())}else Z[B]=T}}}return Z}return Y(U)}async function JG({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:f=!0,arrayStrategy:W="replace"}){let Z=f&&typeof U==="object"&&U!==null&&!Array.isArray(U)?AG($,U,Y):U,B=A||X1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(Y)y$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let F=[$,`.${$}`].filter(Boolean),z=[`${$}.config`,`.${$}.config`].filter(Boolean),j=w?[w,`.${w}`]:[],G=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([B,k$(B,"config"),k$(B,".config"),J?k$(B,J):void 0].filter(Boolean)));for(let h of T){if(Y)y$.info(`Searching for configuration in: ${h}`);let q=[k$(B,"config"),k$(B,".config")].concat(J?[k$(B,J)]:[]).includes(h)?[...F,...z,...j,...G]:[...z,...F,...G,...j];for(let N of q)for(let R of E){let y=k$(h,`${N}${R}`),C=await AJ(y,Z,W);if(C!==null){if(Y)y$.success(`Configuration loaded from: ${y}`);return C}}}if($){let h=k$(PY(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)y$.info(`Checking user config directory: ${h}`);for(let N of q)for(let R of E){let y=k$(h,`${N}${R}`),C=await AJ(y,Z,W);if(C!==null){if(Y)y$.success(`Configuration loaded from user config directory: ${y}`);return C}}}if($){let h=k$(PY(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)y$.info(`Checking user config directory for dotfile configs: ${h}`);for(let N of q)for(let R of E){let y=k$(h,`${N}${R}`),C=await AJ(y,Z,W);if(C!==null){if(Y)y$.success(`Configuration loaded from user config directory dotfile: ${y}`);return C}}}if($){let h=PY(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)y$.info(`Checking user home directory for dotfile configs: ${h}`);for(let N of q)for(let R of E){let y=k$(h,`${N}${R}`),C=await AJ(y,Z,W);if(C!==null){if(Y)y$.success(`Configuration loaded from user home directory: ${y}`);return C}}}try{let h=k$(B,"package.json");if(QB(h)){let q=await import(h),N=q[$];if(!N&&w){if(N=q[w],N&&Y)y$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)y$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return K8(Z,N,W)}catch(R){if(Y)y$.warn("Failed to merge package.json config:",R)}}}catch(h){if(Y)y$.warn("Failed to load package.json:",h)}if(Y)y$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function UG($,w={}){let A=BJ.cwd();while(A.includes("storage"))A=pW(A,"..");let J=pW(A,$||"");if(w?.relative)return WT(BJ.cwd(),J);return J}async function YG(){try{let $=await JG({name:"clarity",alias:"logging",defaultConfig:ZJ,cwd:BJ.cwd()});return{...ZJ,...$||{}}}catch{return ZJ}}function B$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fG(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D0<"u"){let $=D0.type;if($==="renderer"||$==="worker")return!1;return!!(D0.versions&&(D0.versions.node||D0.versions.bun))}return!1}class uB{async format($){let w=await fG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Y8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new uB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??v.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...WJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...WJ};return{...WJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Y8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!B$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,f=1000;while(U<Y)try{try{try{await MT(this.config.logDirectory,UB.F_OK|UB.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await IT(this.config.logDirectory,{recursive:!0,mode:493});else if(Z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Z;else throw Z}}catch(Z){throw console.error("Debug: [writeToFile] Failed to create log directory:",Z),Z}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:V0.from($);try{if(!lA(this.currentLogFile))await mY(this.currentLogFile,"",{mode:420});if(J=JB(this.currentLogFile,"a",420),RT(J,W,{flag:"a"}),AB(J),J!==void 0)nY(J),J=void 0;if((await dw(this.currentLogFile)).size===0){if(await mY(this.currentLogFile,W,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let B=Z;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<Y-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,E);let F=f*2**U;await new Promise((z)=>setTimeout(z,F)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(J!==void 0)try{nY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}U++;let Z=f*2**(U-1);await new Promise((B)=>setTimeout(B,Z))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return gw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return gw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(B$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,f],[,W])=>W.createdAt.getTime()-f.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[f]of J.slice(Y))this.encryptionKeys.delete(f),this.keys.delete(f)}generateKeyId(){return vY(16).toString("hex")}generateKey(){return vY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=vY(16),J=qT("aes-256-gcm",w,A),U=V0.isBuffer($)?$:V0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),B=V0.allocUnsafe(16+W+16);return A.copy(B,0),Y.copy(B,16),f.copy(B,16+Y.length),Z.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let J=fB(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(V0.from(V0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(B$())return;if(!this.shouldWriteToFile())return;let $=await dw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await pA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await dw(A).catch(()=>null))try{if(await YB(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await tA(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await mY(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await dw(A).catch(()=>null))await YB(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await pA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await tA(gw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=wB($),J=KT(w),U=fB();await LT(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),lA(this.currentLogFile))try{let $=JB(this.currentLogFile,"r+");AB($),nY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!B$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await pA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await tA(gw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?k.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||B$())return!1;let $=typeof v.env.NO_COLOR<"u",w=v.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof v.stderr<"u"&&v.stderr.isTTY||typeof v.stdout<"u"&&v.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=v.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${k.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=k.underline(k.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>k.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>k.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>k.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>k.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>k.strikethrough(J)),w}supportsHyperlinks(){if(B$())return!1;let $=v.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=v.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(yT(w)||w.startsWith("./")||w.startsWith("../"))w=CT(w);else return null;return lA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);let{consoleText:Z,fileText:B}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":aB[$],z=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:k.gray(Z),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:k.green(Z),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.error(j),W){let G=W.split(`
|
|
72
|
-
`)
|
|
62
|
+
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
63
|
+
`;return A}}function dh($,w,A={}){return RB($,w,A,new WeakMap)}function RB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return qB($,w,f,Y);if(!w0(w)||!w0($))return w;return ph($,w,A,Y)}function qB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return lh($,w);case"smart":return gh($,w,Y);default:return w}return w}function lh($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>dX(f,Y)))A.push(Y);return A}function gh($,w,A){if(w.length===0)return $;if($.length===0)return w;if(w0(w[0])&&w0($[0]))return th($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function th($,w,A){let Y=[...w];for(let f of $){if(!w0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>w0(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function ph($,w,A,Y){let f=w;if(w0(f)&&Y.has(f))return Y.get(f);let X={...$};if(w0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(w0(W)&&w0(J))X[U]=RB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=qB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function NB($,w,A="replace"){return dh($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function dX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!dX($[A],w[A]))return!1;return!0}if(w0($)&&w0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!dX($[f],w[f]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class yB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=mA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!PA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new wY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new wY($,Error("Configuration must export a valid object"),"unknown");let G={config:NB(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)mA.setWithFileCheck("file",G,$,X);return G}catch(B){throw B instanceof Error?tw.configLoad($,B):tw.configLoad($,Error(String(B)))}};if(U)return lX.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(DX(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return mh(async()=>{return PA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!PA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=DX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=DX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!PA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class MB{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await lX.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!rh(w))throw new AY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new AY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ah},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function sh($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class IB{fileLoader=new yB;envProcessor=new $8;validator=new MB;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)L0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw L0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||YY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let h=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(h)return T.push(e$(j,"package.json")),this.finalizeResult(h,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw tw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${sh(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?iA($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)L0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)L0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?iA($,A,f):A,W=[e$(xw(),".config",$),e$(xw(),".config"),xw()];for(let J of W){if(f)L0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)L0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?iA($,Y,X):Y;try{let J=e$(A,"package.json");if(!dz(J))return null;let B={};try{B=JSON.parse(lz(J,"utf8"))}catch(T){if(X)L0.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)L0.success(`Configuration loaded from package.json: ${j}`);return{config:NB(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)L0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:iA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw tw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return mA.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);mA.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,e$($,"config"),e$($,".config"),w?e$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(e$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[e$(xw(),".config",$),e$(xw(),".config"),xw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function iA($,w,A=!1){let Y=new $8,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((h)=>h.toUpperCase()).join("")}`,`${f}_${j.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let h of T)if(F=YY.env[h],F!==void 0){H=h;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let h=Number(F);if(!Number.isNaN(h))J[B]=h}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((h)=>h.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}var mA,lX,Q2,_2=($)=>$,k2=($,w)=>{for(var A in w)Q2($,A,{get:w[A],enumerable:!0,configurable:!0,set:D2.bind(w,A)})},Z2=($,w)=>()=>($&&(w=$($=0)),w),tW,AB,gw,i1,YB,Jh,Wh,_W,cA,PX,M$,l,Bh,DW,Eh,kW,jh,Th,LX,Fh,ZW,xW,OX,zh,hh,Hh,Gh,uA,fB,Kh,I$,Rh,qh,PW,nA,iX,B$,D,Nh,iW,yh,bW,Mh,Ih,VX,Ch,cW,uW,Sh,QX,Lh,Oh,Vh,Qh,_h,vA,XB,Dh,kh="0.15.6",p$,oA,x1,bX,cX,eA,uX,nX,P1,vX,mX,e0,UB,JB,F0,_0,WB,BB,Zh,Ph,EB,$Y,_q,R$,P,Dq,bh,kq,ch,Zq,xq,nW,Pq,uh,nh,iq,vW,bq,cq,uq,nq,vq,_X,vh,mq,z0,TB,wY,FB,zB,eX,hB,HB,AY,GB,KB,tw,ah,L0,pq,rq,aq;var w8=K$(()=>{mA=new mW,lX=new dW,Q2=Object.defineProperty;tW={};k2(tW,{withErrorRecovery:()=>aW,tryLoadConfig:()=>Yh,loadConfigWithResult:()=>wh,loadConfig:()=>wB,isRetryableError:()=>r2,isConfigNotFoundError:()=>p2,isBunfigError:()=>sW,globalPerformanceMonitor:()=>i1,globalCache:()=>gw,getEnvOrDefault:()=>a2,generateConfigTypes:()=>fh,defaultGeneratedDir:()=>BB,defaultConfigDir:()=>WB,deepMergeWithArrayStrategy:()=>aX,deepMerge:()=>oW,createLibraryConfig:()=>Xh,config:()=>Ah,bunfigPlugin:()=>Uh,applyEnvVarsToConfig:()=>k1,TypeGenerationError:()=>nX,SchemaValidationError:()=>P1,PluginError:()=>mX,PerformanceMonitor:()=>tX,FileSystemError:()=>uX,ErrorFactory:()=>e0,EnvVarError:()=>eA,EnvProcessor:()=>fY,ConfigValidator:()=>sX,ConfigValidationError:()=>bX,ConfigNotFoundError:()=>oA,ConfigMergeError:()=>cX,ConfigLoader:()=>oX,ConfigLoadError:()=>x1,ConfigFileLoader:()=>XY,ConfigCache:()=>gX,CacheUtils:()=>YB,BunfigError:()=>p$,BrowserConfigError:()=>vX,ArrayMergeStrategies:()=>UB});Zh=Z2(async()=>{AB=import.meta.require,gw=new gX,i1=new tX,YB={createKey:x2,isEquivalent:P2,estimateMemoryUsage:i2},Jh=gA(ZX.cwd(),"config"),Wh=gA(ZX.cwd(),"src/generated"),_W=lA.env.CLARITY_LOG_DIR||sz(u2(),"logs"),cA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_W,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},PX=await n2(),M$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},l=M$,Bh=M$.red,DW=M$.green,Eh=M$.yellow,kW=M$.blue,jh=M$.magenta,Th=M$.cyan,LX=M$.white,Fh=M$.gray,ZW=M$.bgRed,xW=M$.bgYellow,OX=M$.bold,zh=M$.dim,hh=M$.italic,Hh=M$.underline,Gh=M$.reset,uA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fB={debug:"\uD83D\uDD0D",info:kW("ℹ"),success:DW("✓"),warning:xW(LX(OX(" WARN "))),error:ZW(LX(OX(" ERROR ")))},Kh=new rA("stacks"),I$=new rA("bunfig",{showTags:!0}),Rh=k$(Z1.cwd(),"config"),qh=k$(Z1.cwd(),"src/generated"),PW=dA.env.CLARITY_LOG_DIR||rz(l2(),"logs"),nA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:PW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iX=await g2(),B$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},D=B$,Nh=B$.red,iW=B$.green,yh=B$.yellow,bW=B$.blue,Mh=B$.magenta,Ih=B$.cyan,VX=B$.white,Ch=B$.gray,cW=B$.bgRed,uW=B$.bgYellow,Sh=B$.bgGray,QX=B$.bold,Lh=B$.dim,Oh=B$.italic,Vh=B$.underline,Qh=B$.strikethrough,_h=B$.reset,vA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XB={debug:"\uD83D\uDD0D",info:bW("ℹ"),success:iW("✓"),warning:uW(VX(QX(" WARN "))),error:cW(VX(QX(" ERROR ")))},Dh=new sA("stacks"),p$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},oA=class extends p${code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},x1=class extends p${code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},bX=class extends p${code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},cX=class extends p${code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},eA=class extends p${code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},uX=class extends p${code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},nX=class extends p${code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},P1=class extends p${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},vX=class extends p${code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},mX=class extends p${code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},e0={configNotFound($,w,A){return new oA($,w,A)},configLoad($,w,A){return new x1($,w,A)},configValidation($,w,A){return new bX($,w,A)},configMerge($,w,A,Y){return new cX($,w,A,Y)},envVar($,w,A,Y){return new eA($,w,A,Y)},fileSystem($,w,A){return new uX($,w,A)},typeGeneration($,w,A){return new nX($,w,A)},schemaValidation($,w,A){return new P1($,w,A)},browserConfig($,w,A,Y){return new vX($,w,A,Y)},plugin($,w,A){return new mX($,w,A)}},UB={replace:"replace",concat:"concat",smart:"smart"},JB=/^https?:\/\//,F0=new sA("bunfig",{showTags:!0}),_0=new oX,WB=Z$(Hw.cwd(),"config"),BB=Z$(Hw.cwd(),"src/generated")});Ph=tA.env.CLARITY_LOG_DIR||R2(xh(),"logs"),EB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ph,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},$Y={...EB},_q=(async()=>{try{let{loadConfig:$}=await Zh().then(()=>tW),w=await $({name:"clarity",alias:"logging",defaultConfig:EB,cwd:tA.cwd()});if(w)Object.assign($Y,w)}catch{}return $Y})();R$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=R$,Dq=R$.red,bh=R$.green,kq=R$.yellow,ch=R$.blue,Zq=R$.magenta,xq=R$.cyan,nW=R$.white,Pq=R$.gray,uh=R$.bgRed,nh=R$.bgYellow,iq=R$.bgGray,vW=R$.bold,bq=R$.dim,cq=R$.italic,uq=R$.underline,nq=R$.strikethrough,vq=R$.reset,_X={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vh={debug:"\uD83D\uDD0D",info:ch("ℹ"),success:bh("✓"),warning:nh(nW(vW(" WARN "))),error:uh(nW(vW(" ERROR ")))};mq=new UY("stacks");z0=class z0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};TB=class TB extends z0{code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};wY=class wY extends z0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};FB=class FB extends z0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};zB=class zB extends z0{code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};eX=class eX extends z0{code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};hB=class hB extends z0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};HB=class HB extends z0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};AY=class AY extends z0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};GB=class GB extends z0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};KB=class KB extends z0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};tw={configNotFound($,w,A){return new TB($,w,A)},configLoad($,w,A){return new wY($,w,A)},configValidation($,w,A){return new FB($,w,A)},configMerge($,w,A,Y){return new zB($,w,A,Y)},envVar($,w,A,Y){return new eX($,w,A,Y)},fileSystem($,w,A){return new hB($,w,A)},typeGeneration($,w,A){return new HB($,w,A)},schemaValidation($,w,A){return new AY($,w,A)},browserConfig($,w,A,Y){return new GB($,w,A,Y)},plugin($,w,A){return new KB($,w,A)}};ah=/^https?:\/\//;L0=new UY("bunfig",{showTags:!0});pq=new IB;rq=e$(YY.cwd(),"config"),aq=e$(YY.cwd(),"src/generated")});var q;var $w=K$(()=>{q={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as $H}from"node:module";import{Resolver as f8}from"node:dns/promises";import{createHash as AH,sign as YH}from"node:crypto";import{createHash as fH}from"node:crypto";import{sign as XH}from"node:crypto";import{generateKeyPairSync as _E,X509Certificate as zH}from"node:crypto";import X8 from"node:os";import U8 from"node:path";import{existsSync as SB,statSync as LB}from"fs";import{existsSync as HH,mkdirSync as zN,readdirSync as hN,readFileSync as GH,writeFileSync as HN}from"fs";import{homedir as rw}from"os";import{dirname as RN,resolve as Y0}from"path";import gY from"process";import{existsSync as OB,statSync as VB}from"fs";import{existsSync as Q8,mkdirSync as KH,readdirSync as RH,writeFileSync as qH}from"fs";import{homedir as aw}from"os";import{dirname as QB,resolve as P$}from"path";import Kw from"process";import{join as NH,relative as yH,resolve as _B}from"path";import VY from"process";import{existsSync as DE,mkdirSync as VN,readdirSync as QN,writeFileSync as _N}from"fs";import{homedir as J8}from"os";import{dirname as ZN,resolve as x$}from"path";import v1 from"process";import{join as MH,relative as IH,resolve as DB}from"path";import QY from"process";import{existsSync as kE,mkdirSync as cN,readdirSync as uN,writeFileSync as nN}from"fs";import{dirname as mN,resolve as _Y}from"path";import _8 from"process";import{Buffer as ww}from"buffer";import{createCipheriv as CH,createDecipheriv as SH,randomBytes as W8}from"crypto";import{closeSync as B8,createReadStream as kB,createWriteStream as LH,existsSync as E8,fsyncSync as ZB,openSync as xB,writeFileSync as OH}from"fs";import{access as VH,constants as PB,mkdir as QH,readdir as JY,rename as iB,stat as sw,unlink as WY,writeFile as j8}from"fs/promises";import{join as ow}from"path";import C$ from"process";import{pipeline as _H}from"stream/promises";import{createGzip as bB}from"zlib";import ew from"process";import x0 from"process";import{Buffer as D0}from"buffer";import{createCipheriv as DH,createDecipheriv as kH,randomBytes as T8}from"crypto";import{closeSync as F8,createReadStream as cB,createWriteStream as ZH,existsSync as BY,fsyncSync as uB,openSync as nB,writeFileSync as xH}from"fs";import{access as PH,constants as vB,mkdir as iH,readdir as EY,rename as mB,stat as $1,unlink as jY,writeFile as z8}from"fs/promises";import{isAbsolute as bH,join as w1,resolve as cH}from"path";import n from"process";import{pipeline as uH}from"stream/promises";import{createGzip as dB}from"zlib";import A1 from"process";import P0 from"process";import TY from"process";import{existsSync as FY}from"fs";import{resolve as h8}from"path";import{existsSync as nH}from"fs";import{existsSync as vH,readdirSync as mH}from"fs";import{extname as H8,resolve as lB}from"path";import dH from"process";import{join as lH,relative as gH,resolve as gB}from"path";import DY from"process";import{Buffer as k0}from"buffer";import{createCipheriv as tH,createDecipheriv as pH,randomBytes as G8}from"crypto";import{closeSync as K8,createReadStream as tB,createWriteStream as rH,existsSync as zY,fsyncSync as pB,openSync as rB,writeFileSync as aH}from"fs";import{access as sH,constants as aB,mkdir as oH,readdir as hY,rename as sB,stat as Y1,unlink as HY,writeFile as R8}from"fs/promises";import{isAbsolute as eH,join as f1,resolve as $G}from"path";import v from"process";import{pipeline as wG}from"stream/promises";import{createGzip as oB}from"zlib";import X1 from"process";import i0 from"process";import GY from"process";import{existsSync as KY}from"fs";import{resolve as q8}from"path";import{existsSync as AG}from"fs";import{exec as I9}from"node:child_process";import TE from"node:fs";import C9 from"node:os";import h0 from"node:path";import hj from"node:process";import{promisify as S9}from"node:util";import B1 from"node:crypto";import b0 from"node:fs";import d8 from"node:path";import{execSync as GE}from"node:child_process";import dY from"node:os";async function KE($,w,A={}){let Y=A.timeoutMs??120000,f=A.intervalMs??3000,X=$.split(".").slice(-2).join("."),U;try{let B=new f8,E=await B.resolveNs(X),j=(await Promise.all(E.map((T)=>B.resolve4(T).catch(()=>[])))).flat();if(j.length>0)U=new f8,U.setServers(j)}catch{}let W=Date.now()+Y,J=U??new f8;for(;;){try{if((await J.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,f))}}class n1{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(n1.PATH_PREFIX);if(w===-1)return;let A=$.slice(w+n1.PATH_PREFIX.length);return this.get(A)}}function NY($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function S8($){return Buffer.from($,"base64url")}function RE($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function qE($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return AH("sha256").update(w).digest("base64url")}function NE($){let{protectedHeader:w,payload:A,privateKey:Y}=$,f=NY(JSON.stringify(w)),X=A===""?"":NY(JSON.stringify(A)),U=`${f}.${X}`,W=YH("sha256",Buffer.from(U),{key:Y,dsaEncoding:"ieee-p1363"});return{protected:f,payload:X,signature:NY(W)}}class OY{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=RE($.accountPublicKey),this.thumbprint=qE(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:A,useJwk:Y}=$,f={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(Y)f.jwk=this.jwk;else f.kid=this.requireKid();let X=NE({protectedHeader:f,payload:A,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(X)}),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let J=U.headers.get("content-type")??"",B;if(J.includes("application/pem-certificate-chain")||J.startsWith("text/"))B=await U.text();else{let E=await U.text();B=E?JSON.parse(E):{}}if(U.status>=400){let E=B??{};throw new LY(`ACME request to ${w} failed (HTTP ${U.status}): ${E.type??""} ${E.detail??""}`.trim(),E,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),A={termsOfServiceAgreed:!0};if($.email)A.contact=[`mailto:${$.email}`];let Y=await this.signedPost({url:w.newAccount,payload:A,useJwk:!0});if(!Y.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=Y.location,this.accountKid}async newOrder($){let w=await this.directory(),A={identifiers:$.map((f)=>({type:"dns",value:f}))},Y=await this.signedPost({url:w.newOrder,payload:A});if(!Y.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:Y.body,orderUrl:Y.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return fH("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getAuthorization($);if(X.status==="valid")return;if(X.status==="invalid"){let U=X.challenges.find((W)=>W.status==="invalid");throw new LY(`Authorization for ${X.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await CB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getOrder($);if(X.status==="valid"){if(!X.certificate)throw Error("ACME order is valid but has no certificate URL");return X.certificate}if(X.status==="invalid")throw Error(`ACME order ${$} became invalid`);await CB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let A=$.challenges.find((Y)=>Y.type===w);if(!A)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return A}}function IE($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],A=w[0];if(!A)return{certPem:`${$.trim()}
|
|
64
|
+
`,chainPem:""};let Y=`${A.trim()}
|
|
65
|
+
`,f=w.slice(1).map((X)=>X.trim()).join(`
|
|
66
|
+
`);return{certPem:Y,chainPem:f?`${f}
|
|
67
|
+
`:""}}function CE($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function CB($){return new Promise((w)=>setTimeout(w,$))}function UH($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function fw($,w){return Buffer.concat([Buffer.from([$]),UH(w.length),w])}function SE($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=[],Y=$;while(Y>0)A.unshift(Y&255),Y>>=8;if(A[0]&128)A.unshift(0);w=Buffer.from(A)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return fw(2,w)}function Gw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let A=[40*w[0]+w[1]];for(let Y=2;Y<w.length;Y++){let f=w[Y],X=[f&127];f=Math.floor(f/128);while(f>0)X.unshift(f&127|128),f=Math.floor(f/128);A.push(...X)}return fw(6,Buffer.from(A))}function A0(...$){return fw(48,Buffer.concat($))}function L8(...$){return fw(49,Buffer.concat($))}function O8($){return fw(3,Buffer.concat([Buffer.from([0]),$]))}function LE($){return fw(4,$)}function OE($){return fw(12,Buffer.from($,"utf8"))}function V8($,w,A){let Y=128|(A?32:0)|$;return fw(Y,w)}function FH($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let A=S8(w.x),Y=S8(w.y);if(A.length!==32||Y.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${A.length} y=${Y.length}`);return Buffer.concat([Buffer.from([4]),A,Y])}function VE($){let{domains:w,publicKey:A,privateKey:Y}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let f=A0(L8(A0(Gw(EH),OE(w[0])))),X=A0(A0(Gw(JH),Gw(WH)),O8(FH(A))),U=w.map((h)=>V8(2,Buffer.from(h,"ascii"),!1)),W=A0(...U),J=A0(Gw(TH),LE(W)),B=A0(J),E=A0(Gw(jH),L8(B)),j=V8(0,E,!0),T=A0(SE(0),f,X,j),F=XH("sha256",T,Y),H=A0(Gw(BH));return A0(T,H,O8(F))}function QE($){return VE($).toString("base64url")}function hH($){if($){let{createPrivateKey:f,createPublicKey:X}=wH("node:crypto"),U=f($),W=X(U);return{privateKey:U,publicKey:W,pem:$}}let{privateKey:w,publicKey:A}=_E("ec",{namedCurve:"P-256"}),Y=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:A,pem:Y}}async function l8($){let{domains:w,method:A}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(A==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((j)=>j.startsWith("*."))&&A!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let Y=$.directoryUrl??($.staging===!1?ME:yE),f=hH($.accountKeyPem),X=new OY({directoryUrl:Y,accountKey:f.privateKey,accountPublicKey:f.publicKey});await X.newAccount({email:$.email});let{order:U,orderUrl:W}=await X.newOrder(w),J=$.http01Store??lY,B=[],E=[];try{for(let y of U.authorizations){let S=await X.getAuthorization(y);if(S.status==="valid")continue;let w$=OY.selectChallenge(S,A);if(A==="dns-01"){let d$=CE(S.identifier.value),_$=X.dns01TxtValue(w$.token);await $.dnsProvider.setTxt(d$,_$),B.push({name:d$,value:_$}),await KE(d$,_$,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else J.add(w$.token,X.keyAuthorization(w$.token)),E.push(w$.token);await X.notifyChallengeReady(w$.url),await X.pollAuthorization(y,{timeoutMs:$.timeoutMs})}let{privateKey:j,publicKey:T}=_E("ec",{namedCurve:"P-256"}),F=QE({domains:w,publicKey:T,privateKey:j});await X.finalizeOrder(U.finalize,F);let H=await X.pollOrder(W,{timeoutMs:$.timeoutMs}),h=await X.downloadCertificate(H),{certPem:G,chainPem:K}=IE(h),R=K?`${G}${K}`:G,M=j.export({format:"pem",type:"pkcs8"}).toString(),N=new Date(new zH(G).validTo);return{certPem:G,keyPem:M,chainPem:K,fullChainPem:R,accountKeyPem:f.pem,notAfter:N}}finally{for(let{name:j,value:T}of B)await $.dnsProvider?.removeTxt(j,T).catch(()=>{});for(let j of E)J.remove(j)}}class ZE{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!SB($))return!0;return LB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=SB(A)?LB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class xE{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function XG($,w){this[$]=fG.bind(null,w)}class t8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!OB($))return!0;return VB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=OB(A)?VB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class p8{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function WG($,w={}){let A=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return A?`${$}:${A}`:$}function BG($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function EG($){return $.getStats().size*2}function r8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&s(w[0])&&"id"in w[0]&&w[0].id===3&&s(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(s(w)&&s($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(s($)&&"arr"in $&&Array.isArray($.arr)&&s(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&s(w[0])&&s($[0])){let Y=[...w];for(let f of $)if(s(f)&&"name"in f){if(!Y.find((X)=>s(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(s(f)&&"path"in f){if(!Y.find((X)=>s(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>ZY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!s(w)||!s($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(s(f)&&s(A[Y]))A[Y]=r8(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&s(f[0])&&s(A[Y][0])){let X=[...f];for(let U of A[Y])if(s(U)&&"name"in U){if(!X.find((W)=>s(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(s(U)&&"path"in U){if(!X.find((W)=>s(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>ZY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function ZY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!ZY($[A],w[A]))return!1;return!0}if(s($)&&s(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!ZY($[f],w[f]))return!1}return!0}return!1}function s($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function jG($,w){if(!kE($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return r8(w,Y)}catch{return null}}catch{return null}}async function TG({name:$="",cwd:w,defaultConfig:A}){let Y=w||_8.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=_Y(Y,`${U}${W}`),B=await jG(J,A);if(B!==null)return B}try{let U=_Y(Y,"package.json");if(kE(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return r8(A,W)}catch{}}}catch{}return A}function FG($,w={}){let A=QY.cwd();while(A.includes("storage"))A=DB(A,"..");let Y=DB(A,$||"");if(w?.relative)return IH(QY.cwd(),Y);return Y}async function zG(){try{let $=await TG({name:"clarity",defaultConfig:MY,cwd:QY.cwd(),endpoint:"",headers:{}});return{...MY,...$}}catch{return MY}}function Y$(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hG(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof x0<"u"){let $=x0.type;if($==="renderer"||$==="worker")return!1;return!!(x0.versions&&(x0.versions.node||x0.versions.bun))}return!1}class iE{async format($){let w=await hG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:ew.pid,hostname:w(),environment:ew.env.NODE_ENV||"development",platform:ew.platform,version:ew.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ew.env.NODE_ENV||ew.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...k8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new iE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??C$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...IY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...IY};return{...IY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:k8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await VH(this.config.logDirectory,PB.F_OK|PB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await QH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:ww.from($);try{if(!E8(this.currentLogFile))await j8(this.currentLogFile,"",{mode:420});if(Y=xB(this.currentLogFile,"a",420),OH(Y,W,{flag:"a"}),ZB(Y),Y!==void 0)B8(Y),Y=void 0;if((await sw(this.currentLogFile)).size===0){if(await j8(this.currentLogFile,W,{flag:"w",mode:420}),(await sw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{B8(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ow(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 ow(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return ow(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Y$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return W8(16).toString("hex")}generateKey(){return W8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=W8(16),Y=CH("aes-256-gcm",w,A),f=ww.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:ww.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=bB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(ww.from(ww.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Y$())return;let $=await sw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await JY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await sw(A).catch(()=>null))try{if(await iB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await WY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await j8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await sw(A).catch(()=>null))await iB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await JY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await WY(ow(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=kB($),Y=LH(w),f=bB();await _H(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),E8(this.currentLogFile))try{let $=xB(this.currentLogFile,"r+");ZB($),B8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Y$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await JY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await WY(ow(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=C$.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${g.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!Y$()){let B=tE[$],E=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:g.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:g.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
68
|
+
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:g.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!Y$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let J=`${X} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
69
|
+
`;if(W)J+=`${W}
|
|
70
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!Y$()){let A=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:g.blue("◐"),tag:A,message:`${g.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),J=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)J+=` ${JSON.stringify(A)}`;if(J+=`
|
|
71
|
+
`,J=J.replace(this.ANSI_PATTERN,""),this.fancy&&!Y$()){let B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:g.green("✓"),tag:B,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Y$())console.error(J.trim());await this.writeToFile(J)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new xY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(Y$())throw Error("createReadStream is not supported in browser environments");if(!E8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return kB(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=ww.isBuffer($)?$:ww.from($,"base64"),f=Y.slice(0,16),X=Y.slice(-16),U=Y.slice(16,-16),W=SH("aes-256-gcm",A,f);return W.setAuthTag(X),ww.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Y$()}isServerMode(){return!Y$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w);if(this.fancy&&!Y$()){let X=$.split(`
|
|
72
|
+
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:g.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(W)})),B.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(J),showTimestamp:!1}))}else if(!Y$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let f=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
73
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(Y$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();C$.stdin.removeListener("data",A);try{if(typeof C$.stdin.setRawMode==="function")C$.stdin.setRawMode(!1)}catch{}C$.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof C$.stdin.setRawMode==="function")C$.stdin.setRawMode(!0)}catch{}C$.stdin.resume(),C$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,X=0;if(A=$.replace(f,(U,W)=>{if(W==="%")return"%";if(X>=w.length)return U;let J=w[X++];switch(W){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 U}}),X<w.length)A+=` ${w.slice(X).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!Y$()){let f=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",X=g.blue("◐");console.error(`${X} ${f} ${g.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
74
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||Y$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Y,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Y$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),f!==void 0)this.activeProgressBar.message=f;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Y$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Y$())return;C$.stdout.write(`${"\r".padEnd(C$.stdout.columns||80)}\r`),this.log(f,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||Y$()||!C$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=g.green("━".repeat(Y)),U=g.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=w||A===100?g.green("✓"):g.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=C$.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,C$.stdout.write($.lastRenderedLine),w)C$.stdout.write(`
|
|
75
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y$()||!C$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Y$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await JY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=ow(this.config.logDirectory,Y);if($.before)try{if((await sw(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await WY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function yY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&m(w[0])&&"id"in w[0]&&w[0].id===3&&m(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(m(w)&&m($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(m($)&&"arr"in $&&Array.isArray($.arr)&&m(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&m(w[0])&&m($[0])){let Y=[...w];for(let f of $)if(m(f)&&"name"in f){if(!Y.find((X)=>m(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(m(f)&&"path"in f){if(!Y.find((X)=>m(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>PY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!m(w)||!m($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(m(f)&&m(A[Y]))A[Y]=yY(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&m(f[0])&&m(A[Y][0])){let X=[...f];for(let U of A[Y])if(m(U)&&"name"in U){if(!X.find((W)=>m(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(m(U)&&"path"in U){if(!X.find((W)=>m(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>PY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function a8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:yY($,w);if(Array.isArray($))return A==="replace"?w:yY($,w);if(!m(w)||!m($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=yY(U,X);else if(m(X)&&m(U))Y[f]=a8(U,X,A);else Y[f]=X}return Y}function PY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!PY($[A],w[A]))return!1;return!0}if(m($)&&m(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!PY($[f],w[f]))return!1}return!0}return!1}function m($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function RY($,w,A="replace"){if(!DE($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return a8(w,f,A)}catch{return null}}catch{return null}}function HG($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((h)=>h.toUpperCase()).join("_")}`;if(A)L$.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let h=v1.env[F]||v1.env[H];if(h!==void 0){if(A)L$.info(`Using environment variable ${h?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(h);else if(typeof E==="boolean")J[B]=h.toLowerCase()==="true";else if(Array.isArray(E))try{let G=JSON.parse(h);if(Array.isArray(G))J[B]=G;else J[B]=h.split(",").map((K)=>K.trim())}catch{J[B]=h.split(",").map((G)=>G.trim())}else J[B]=h}}}return J}return X(f)}async function GG({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?HG($,f,X):f,B=A||v1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)L$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],h=Array.from(new Set([B,x$(B,"config"),x$(B,".config"),Y?x$(B,Y):void 0].filter(Boolean)));for(let G of h){if(X)L$.info(`Searching for configuration in: ${G}`);let K=[x$(B,"config"),x$(B,".config")].concat(Y?[x$(B,Y)]:[]).includes(G)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let R of K)for(let M of E){let N=x$(G,`${R}${M}`),y=await RY(N,J,W);if(y!==null){if(X)L$.success(`Configuration loaded from: ${N}`);return y}}}if($){let G=x$(J8(),".config",$),K=["config",`${$}.config`];if(w)K.push(`${w}.config`);if(X)L$.info(`Checking user config directory: ${G}`);for(let R of K)for(let M of E){let N=x$(G,`${R}${M}`),y=await RY(N,J,W);if(y!==null){if(X)L$.success(`Configuration loaded from user config directory: ${N}`);return y}}}if($){let G=x$(J8(),".config"),K=[`.${$}.config`];if(w)K.push(`.${w}.config`);if(X)L$.info(`Checking user config directory for dotfile configs: ${G}`);for(let R of K)for(let M of E){let N=x$(G,`${R}${M}`),y=await RY(N,J,W);if(y!==null){if(X)L$.success(`Configuration loaded from user config directory dotfile: ${N}`);return y}}}if($){let G=J8(),K=[`.${$}.config`,`.${$}`];if(w)K.push(`.${w}.config`),K.push(`.${w}`);if(X)L$.info(`Checking user home directory for dotfile configs: ${G}`);for(let R of K)for(let M of E){let N=x$(G,`${R}${M}`),y=await RY(N,J,W);if(y!==null){if(X)L$.success(`Configuration loaded from user home directory: ${N}`);return y}}}try{let G=x$(B,"package.json");if(DE(G)){let K=await import(G),R=K[$];if(!R&&w){if(R=K[w],R&&X)L$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(X)L$.success(`Configuration loaded from package.json: ${R===K[$]?$:w}`);return a8(J,R,W)}catch(M){if(X)L$.warn("Failed to merge package.json config:",M)}}}catch(G){if(X)L$.warn("Failed to load package.json:",G)}if(X)L$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function KG($,w={}){let A=VY.cwd();while(A.includes("storage"))A=_B(A,"..");let Y=_B(A,$||"");if(w?.relative)return yH(VY.cwd(),Y);return Y}async function RG(){try{let $=await GG({name:"clarity",alias:"logging",defaultConfig:CY,cwd:VY.cwd()});return{...CY,...$||{}}}catch{return CY}}function j$(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qG(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof P0<"u"){let $=P0.type;if($==="renderer"||$==="worker")return!1;return!!(P0.versions&&(P0.versions.node||P0.versions.bun))}return!1}class bE{async format($){let w=await qG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:A1.pid,hostname:w(),environment:A1.env.NODE_ENV||"development",platform:A1.platform,version:A1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:A1.env.NODE_ENV||A1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Z8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new bE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...SY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...SY};return{...SY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Z8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!j$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await PH(this.config.logDirectory,vB.F_OK|vB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await iH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:D0.from($);try{if(!BY(this.currentLogFile))await z8(this.currentLogFile,"",{mode:420});if(Y=nB(this.currentLogFile,"a",420),xH(Y,W,{flag:"a"}),uB(Y),Y!==void 0)F8(Y),Y=void 0;if((await $1(this.currentLogFile)).size===0){if(await z8(this.currentLogFile,W,{flag:"w",mode:420}),(await $1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{F8(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return w1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return w1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(j$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return T8(16).toString("hex")}generateKey(){return T8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=T8(16),Y=DH("aes-256-gcm",w,A),f=D0.isBuffer($)?$:D0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=D0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=dB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(D0.from(D0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(j$())return;if(!this.shouldWriteToFile())return;let $=await $1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await EY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await $1(A).catch(()=>null))try{if(await mB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await z8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await $1(A).catch(()=>null))await mB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await EY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await jY(w1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=cB($),Y=ZH(w),f=dB();await uH(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),BY(this.currentLogFile))try{let $=nB(this.currentLogFile,"r+");uB($),F8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!j$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await EY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await jY(w1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?k.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||j$())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=n.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${k.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=k.underline(k.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>k.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>k.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>k.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>k.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>k.strikethrough(Y)),w}supportsHyperlinks(){if(j$())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=n.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(bH(w)||w.startsWith("./")||w.startsWith("../"))w=cH(w);else return null;return BY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":pE[$],T=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:k.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:k.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
76
|
+
`);for(let h of H)if(h.trim()&&!h.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:k.gray(` ${h}`),level:$,showTimestamp:!1}))}break}}else if(!j$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
73
77
|
`;if(W)E+=`${W}
|
|
74
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(
|
|
75
|
-
`);if(this[
|
|
76
|
-
`,
|
|
77
|
-
`),
|
|
78
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
79
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
80
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
81
|
-
|
|
82
|
-
`;for(let
|
|
83
|
-
`,A+=` Type: ${
|
|
84
|
-
`,A+=` Description: ${
|
|
85
|
-
`,A+=` Example: ${
|
|
78
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(f,X)=>{},finish:(f)=>{},interrupt:(f,X)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!j$()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!j$()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,X="info")=>{if(!j$()&&n.stdout.isTTY)n.stdout.write(`
|
|
79
|
+
`);if(this[X==="warning"?"warn":X](f),this.activeProgressBar&&this.shouldStyleConsole()&&!j$()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":k.blue("◐"),tag:A,message:`${k.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),J=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)J+=` ${JSON.stringify(A)}`;if(J+=`
|
|
80
|
+
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":k.green("✓"),tag:B,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!j$())console.error(J.trim());if(this.shouldWriteToFile())await this.writeToFile(J)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new iY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(j$())throw Error("createReadStream is not supported in browser environments");if(!BY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return cB(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=D0.isBuffer($)?$:D0.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=kH("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=D0.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return j$()}isServerMode(){return!j$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
81
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:k.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(E),showTimestamp:!1}))}else if(!j$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
82
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(j$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${k.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();n.stdin.removeListener("data",A);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${k.blue("◐")} `;console.error(`${W}${U} ${k.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=k.green("━".repeat(Y)),U=k.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?k.green("✓"):k.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=n.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,n.stdout.write($.lastRenderedLine),w)n.stdout.write(`
|
|
84
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||j$()||!n.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(j$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=w1(this.config.logDirectory,Y);if($.before)try{if((await $1(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await jY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function cE($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function uE($){return $ instanceof r$}function NG($){return $ instanceof bY}function yG($){if(uE($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class tY{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return g1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=TY.env[J]||(B?TY.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=TY.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof cY)throw j;throw Yw.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Yw.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(TY.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
85
|
+
|
|
86
|
+
`;for(let Y of $)A+=`${Y.key}
|
|
87
|
+
`,A+=` Type: ${Y.type}
|
|
88
|
+
`,A+=` Description: ${Y.description}
|
|
89
|
+
`,A+=` Example: ${Y.example}
|
|
86
90
|
|
|
87
91
|
`;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
|
|
88
92
|
|
|
89
93
|
`;A+=`| Variable | Type | Description | Example |
|
|
90
94
|
`,A+=`|----------|------|-------------|----------|
|
|
91
|
-
`;for(let
|
|
92
|
-
`;return A}}function BG($,w){let A=pB("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function mB($,w,A={}){return dB($,w,A,new WeakMap)}function dB($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let W=f($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return gB($,w,U,J);if(!$0(w)||!$0($))return w;return zG($,w,A,J)}function gB($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return EG($,w);case"smart":return FG($,w,J);default:return w}return w}function EG($,w){let A=[...w];for(let J of $)if(!A.some((U)=>J8(U,J)))A.push(J);return A}function FG($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return jG($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function jG($,w,A){let J=[...w];for(let U of $){if(!$0(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let W of Y)if(W in U){if(J.find((Z)=>$0(Z)&&(W in Z)&&Z[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function zG($,w,A,J){let U=w;if($0(U)&&J.has(U))return J.get(U);let Y={...$};if($0(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let W=U[f],Z=Y[f];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){Y[f]=W;continue}if($0(W)&&$0(Z))Y[f]=dB(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=gB(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function R8($,w,A="replace"){return mB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function J8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!J8($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!J8($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class SJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:W=!1}=A;if(U){let B=sw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let Z=async()=>{if(!aA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),F=E.default||E,z="default"in E,j=Object.keys(E).length>0;if(!z&&!j)throw new _1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new _1($,Error("Configuration must export a valid object"),"unknown");let G={config:R8(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)sw.setWithFileCheck("file",G,$,Y);return G}catch(B){throw B instanceof Error?o0.configLoad($,B):o0.configLoad($,Error(String(B)))}};if(f)return Q1.track("loadFromPath",Z,{path:$});return Z()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(dY(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return vB(async()=>{return aA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!aA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=dY($,`${Y}${f}`);if(await this.checkFileAccess(W))J.push(W)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let W=dY($,f);if(await this.checkFileAccess(W))J.push(W)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!aA($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class M8{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,B=async()=>{let E=[],F=[],z={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,z);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],z);else return this.validateWithJSONSchema($,w,z)}catch(j){return E.push({path:"",message:`Validation failed: ${j}`,rule:"system"}),{isValid:!1,errors:E,warnings:F}}};if(W)return await Q1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!ST(w))throw new D1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new D1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(f)){if(J.push({path:A,message:`Expected type ${W.join(" or ")}, got ${f}`,expected:W.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let W=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let W of w.required)if(!(W in f)){if(J.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[W,Z]of Object.entries(w.properties))if(W in f){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,B,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let Z of Object.keys(f))if(!W.has(Z))U.push({path:A?`${A}.${Z}`:Z,message:`Additional property '${Z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),W=this.validateWithRule(f,Y,Y.path);if(J.push(...W),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:oB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class I8{fileLoader=new SJ;envProcessor=new LJ;validator=new M8;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let Z=this.checkCache(f.name||"",f);if(Z)return Z}let W;try{W=await this.loadConfigurationStrategies(f,!0,A)}catch(Z){let B=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(B)throw Z;W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(Z instanceof Error&&Z.name==="ConfigLoadError"){let E=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),F=!E&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),z=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(B&&(z||E))throw Z;if(F&&(!B||!z))W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Z.message}`]};else throw Z}else W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Z instanceof Error?Z.message:String(Z)}`]}}if(U||Y)await this.validateConfiguration(W.config,U,Y,f.name);if(A?.enabled&&W)this.cacheResult(f.name||"",W,A,f);if(J?.enabled){let Z={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(Z);if(J.slowThreshold&&Z.duration>J.slowThreshold)E0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw E0.error(`Configuration loading failed after ${Z}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:W,checkEnv:Z=!0,arrayStrategy:B="replace",verbose:E=!1}=$,F=Y||Fw.cwd(),z=[],j=await this.loadLocalConfiguration(J,U,F,f,W,B,E,Z,A);if(j)return z.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(j,z,Z,J,E);let G=await this.loadHomeConfiguration(J,U,W,B,E,Z);if(G)return z.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(G,z,Z,J,E);let T=await this.loadPackageJsonConfiguration(J,U,F,W,B,E,Z);if(T)return z.push(Q$(F,"package.json")),this.finalizeResult(T,z,Z,J,E);if(z.push(...this.getAllSearchPaths(J,U,F,f)),w)throw o0.configNotFound(J,z,U);return{...await this.applyEnvironmentVariables(J,W,Z,E),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let B=W?V1($,U,f):U,E=this.getLocalDirectories(A,J);for(let F of E){if(f)E0.info(`Searching for configuration in: ${F}`);let z=this.fileLoader.generateConfigPaths($,F,w),j=await this.fileLoader.tryLoadFromPaths(z,B,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(j){if(f)E0.success(`Configuration loaded from: ${j.source.path}`);return j}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?V1($,A,U):A,W=[Q$(uw(),".config",$),Q$(uw(),".config"),uw()];for(let Z of W){if(U)E0.info(`Checking home directory: ${Z}`);let B=this.fileLoader.generateConfigPaths($,Z,w),E=await this.fileLoader.tryLoadFromPaths(B,f,{arrayStrategy:J,verbose:U});if(E){if(U)E0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?V1($,J,Y):J;try{let Z=Q$(A,"package.json");if(!w8(Z))return null;let B=await import(Z),E=B[$],F=$;if(!E&&w)E=B[w],F=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(Y)E0.success(`Configuration loaded from package.json: ${F}`);return{config:R8(W,E,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)E0.warn("Failed to load package.json:",[Z instanceof Error?Z:Error(String(Z))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:V1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw o0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return sw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);sw.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Q$($,"config"),Q$($,".config"),w?Q$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(Q$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[Q$(uw(),".config",$),Q$(uw(),".config"),uw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function TB($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function HG($){return x0.loadConfig({...$,__strictErrorHandling:!0})}async function lB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await x0.loadConfig($);else J=await x0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)E0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let f=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x0.applyEnvironmentVariables(f.name||"",w,!0,f.verbose||!1))?.config??w;return w}}async function TG($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&TB(A)))return(await x0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await x0.loadConfig({...$,cwd:$.cwd||Fw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&TB(w)))return(await x0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function GG($,w,A="replace"){let J=new SJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function V1($,w,A=!1){let J=new LJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],j,G;for(let T of z)if(j=Fw.env[T],j!==void 0){G=T;break}if(j!==void 0&&G)if(typeof E==="boolean")Z[B]=["true","1","yes"].includes(j.toLowerCase());else if(typeof E==="number"){let T=Number(j);if(!Number.isNaN(T))Z[B]=T}else if(Array.isArray(E))try{Z[B]=JSON.parse(j)}catch{Z[B]=j.split(",").map((T)=>T.trim())}else Z[B]=j;else if(E&&typeof E==="object"&&!Array.isArray(E))Z[B]=Y(E,F)}return Z}return Y(w)}function hG($){let w=Q$(Fw.cwd(),$.configDir),A=Q$(Fw.cwd(),$.generatedDir),J=Q$(A,"config-types.ts");if(!w8(lW(J)))UT(lW(J),{recursive:!0,mode:511});let U=w8(w)?YT(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${lG}
|
|
93
|
-
export type ConfigNames = ${
|
|
94
|
-
`;
|
|
95
|
-
${
|
|
95
|
+
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
96
|
+
`;return A}}function MG($,w){let A=lE("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function nE($,w,A={}){return vE($,w,A,new WeakMap)}function vE($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return mE($,w,f,Y);if(!f0(w)||!f0($))return w;return LG($,w,A,Y)}function mE($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return IG($,w);case"smart":return CG($,w,Y);default:return w}return w}function IG($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>D8(f,Y)))A.push(Y);return A}function CG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(f0(w[0])&&f0($[0]))return SG($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function SG($,w,A){let Y=[...w];for(let f of $){if(!f0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>f0(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function LG($,w,A,Y){let f=w;if(f0(f)&&Y.has(f))return Y.get(f);let X={...$};if(f0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(f0(W)&&f0(J))X[U]=vE(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=mE(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function s8($,w,A="replace"){return nE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function D8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!D8($[A],w[A]))return!1;return!0}if(f0($)&&f0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!D8($[f],w[f]))return!1}return!0}return!1}function f0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class pY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=J1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!FY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new m1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new m1($,Error("Configuration must export a valid object"),"unknown");let H={config:s8(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)J1.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Yw.configLoad($,B):Yw.configLoad($,Error(String(B)))}};if(U)return g1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(h8(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return cE(async()=>{return FY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!FY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=h8($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=h8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!FY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class o8{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await g1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!nH(w))throw new d1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new d1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:aE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class e8{fileLoader=new pY;envProcessor=new tY;validator=new o8;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)H0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw H0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Kw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let h=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(h)return T.push(P$(j,"package.json")),this.finalizeResult(h,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Yw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?c1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)H0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)H0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?c1($,A,f):A,W=[P$(aw(),".config",$),P$(aw(),".config"),aw()];for(let J of W){if(f)H0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)H0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?c1($,Y,X):Y;try{let J=P$(A,"package.json");if(!Q8(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)H0.success(`Configuration loaded from package.json: ${j}`);return{config:s8(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)H0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:c1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Yw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return J1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);J1.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,P$($,"config"),P$($,".config"),w?P$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(P$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[P$(aw(),".config",$),P$(aw(),".config"),aw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function eB($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function OG($){return c0.loadConfig({...$,__strictErrorHandling:!0})}async function dE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await c0.loadConfig($);else Y=await c0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)H0.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let U=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await c0.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function VG($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await c0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&eB(A)))return(await c0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await c0.loadConfig({...$,cwd:$.cwd||Kw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&eB(w)))return(await c0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function QG($,w,A="replace"){let Y=new pY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function c1($,w,A=!1){let Y=new tY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((h)=>h.toUpperCase()).join("")}`,`${f}_${j.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let h of T)if(F=Kw.env[h],F!==void 0){H=h;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let h=Number(F);if(!Number.isNaN(h))J[B]=h}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((h)=>h.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function _G($){let w=P$(Kw.cwd(),$.configDir),A=P$(Kw.cwd(),$.generatedDir),Y=P$(A,"config-types.ts");if(!Q8(QB(Y)))KH(QB(Y),{recursive:!0,mode:511});let f=Q8(w)?RH(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${U9}
|
|
97
|
+
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
98
|
+
`;qH(Y,X,{mode:438})}function DG($){let w=null,A=null,Y=()=>{if(!A)A=dE($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)H0.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function kG($){let w=lB(dH.cwd(),$?.configDir||"./config");function A(){if(!vH(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=mH(w).filter((J)=>f.has(H8(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=H8(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=H8(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((J)=>J.base),U=X.length?X.map((J)=>`'${J}'`).join(" | "):"string",W=f.length?`{
|
|
99
|
+
${f.map((J)=>{let B=lB(w,J.file).replace(/\\/g,"/");return` '${J.base}': typeof import('${B}').default`}).join(`,
|
|
96
100
|
`)}
|
|
97
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
101
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
98
102
|
export type ConfigByName = ${W}
|
|
99
103
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
100
104
|
export type ConfigOf = Config
|
|
101
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function tG($,w={}){let A=jJ.cwd();while(A.includes("storage"))A=WB(A,"..");let J=WB(A,$||"");if(w?.relative)return DT(jJ.cwd(),J);return J}function F$(){if(k0.env.NODE_ENV==="test"||k0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function aG(){if(k0.env.NODE_ENV==="test"||k0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k0<"u"){let $=k0.type;if($==="renderer"||$==="worker")return!1;return!!(k0.versions&&(k0.versions.node||k0.versions.bun))}return!1}class AE{async format($){let w=await aG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:rw.pid,hostname:w(),environment:rw.env.NODE_ENV||"development",platform:rw.platform,version:rw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rw.env.NODE_ENV||rw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class VJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...KJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new AE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...$8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$8};return{...$8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:KJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,U=0,Y=3,f=1000;while(U<Y)try{try{try{await bT(this.config.logDirectory,jB.F_OK|jB.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await iT(this.config.logDirectory,{recursive:!0,mode:493});else if(Z.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Z;else throw Z}}catch(Z){throw console.error("Debug: [writeToFile] Failed to create log directory:",Z),Z}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O0.from($);try{if(!sA(this.currentLogFile))await tY(this.currentLogFile,"",{mode:420});if(J=FB(this.currentLogFile,"a",420),PT(J,W,{flag:"a"}),EB(J),J!==void 0)pY(J),J=void 0;if((await pw(this.currentLogFile)).size===0){if(await tY(this.currentLogFile,W,{flag:"w",mode:420}),(await pw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let B=Z;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<Y-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,E);let F=f*2**U;await new Promise((z)=>setTimeout(z,F)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(J!==void 0)try{pY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}U++;let Z=f*2**(U-1);await new Promise((B)=>setTimeout(B,Z))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(J){throw console.error("Debug: [writeToFile] Error in operation:",J),J}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 tw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return tw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return tw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((J)=>{console.error("Error rotating keys:",J)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let J=Array.from(this.encryptionKeys.entries()).sort(([,f],[,W])=>W.createdAt.getTime()-f.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,Y=Math.max(1,U);if(J.length>Y)for(let[f]of J.slice(Y))this.encryptionKeys.delete(f),this.keys.delete(f)}generateKeyId(){return lY(16).toString("hex")}generateKey(){return lY(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=lY(16),J=kT("aes-256-gcm",w,A),U=O0.isBuffer($)?$:O0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),B=O0.allocUnsafe(16+W+16);return A.copy(B,0),Y.copy(B,16),f.copy(B,16+Y.length),Z.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let J=HB(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(O0.from(O0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F$())return;if(!this.shouldWriteToFile())return;let $=await pw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await oA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await pw(A).catch(()=>null))try{if(await zB(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await eA(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await tY(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await pw(A).catch(()=>null))await zB(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await oA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await eA(tw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=BB($),J=xT(w),U=HB();await vT(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),sA(this.currentLogFile))try{let $=FB(this.currentLogFile,"r+");EB($),pY($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await oA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await eA(tw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=n.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${b.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=b.underline(b.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>b.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>b.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>b.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>b.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>b.strikethrough(J)),w}supportsHyperlinks(){if(F$())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=n.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(cT(w)||w.startsWith("./")||w.startsWith("../"))w=uT(w);else return null;return sA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);let{consoleText:Z,fileText:B}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":w2[$],z=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:b.gray(Z),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:b.green(Z),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.error(j),W){let G=W.split(`
|
|
102
|
-
`);for(let
|
|
105
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function W9($,w={}){let A=DY.cwd();while(A.includes("storage"))A=gB(A,"..");let Y=gB(A,$||"");if(w?.relative)return gH(DY.cwd(),Y);return Y}function F$(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E9(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i0<"u"){let $=i0.type;if($==="renderer"||$==="worker")return!1;return!!(i0.versions&&(i0.versions.node||i0.versions.bun))}return!1}class $j{async format($){let w=await E9(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:X1.pid,hostname:w(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...uY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new $j,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??v.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...C8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...C8};return{...C8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:uY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await sH(this.config.logDirectory,aB.F_OK|aB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await oH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:k0.from($);try{if(!zY(this.currentLogFile))await R8(this.currentLogFile,"",{mode:420});if(Y=rB(this.currentLogFile,"a",420),aH(Y,W,{flag:"a"}),pB(Y),Y!==void 0)K8(Y),Y=void 0;if((await Y1(this.currentLogFile)).size===0){if(await R8(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(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{K8(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return f1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return f1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return f1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return G8(16).toString("hex")}generateKey(){return G8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=G8(16),Y=tH("aes-256-gcm",w,A),f=k0.isBuffer($)?$:k0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=k0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=oB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(k0.from(k0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F$())return;if(!this.shouldWriteToFile())return;let $=await Y1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await hY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await Y1(A).catch(()=>null))try{if(await sB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await HY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await R8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await Y1(A).catch(()=>null))await sB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await hY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await HY(f1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=tB($),Y=rH(w),f=oB();await wG(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),zY(this.currentLogFile))try{let $=rB(this.currentLogFile,"r+");pB($),K8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await hY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await HY(f1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F$())return!1;let $=typeof v.env.NO_COLOR<"u",w=v.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof v.stderr<"u"&&v.stderr.isTTY||typeof v.stdout<"u"&&v.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=v.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${i.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=i.underline(i.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>i.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>i.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>i.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>i.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>i.strikethrough(Y)),w}supportsHyperlinks(){if(F$())return!1;let $=v.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=v.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(eH(w)||w.startsWith("./")||w.startsWith("../"))w=$G(w);else return null;return zY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":h9[$],T=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:i.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:i.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
106
|
+
`);for(let h of H)if(h.trim()&&!h.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:i.gray(` ${h}`),level:$,showTimestamp:!1}))}break}}else if(!F$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
103
107
|
`;if(W)E+=`${W}
|
|
104
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(
|
|
105
|
-
`);if(this[
|
|
106
|
-
`,
|
|
107
|
-
`),
|
|
108
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
109
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
110
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!
|
|
111
|
-
|
|
112
|
-
`;for(let
|
|
113
|
-
`,A+=` Type: ${
|
|
114
|
-
`,A+=` Description: ${
|
|
115
|
-
`,A+=` Example: ${
|
|
108
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(f,X)=>{},finish:(f)=>{},interrupt:(f,X)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!F$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!F$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,X="info")=>{if(!F$()&&v.stdout.isTTY)v.stdout.write(`
|
|
109
|
+
`);if(this[X==="warning"?"warn":X](f),this.activeProgressBar&&this.shouldStyleConsole()&&!F$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:A,message:`${i.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),J=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)J+=` ${JSON.stringify(A)}`;if(J+=`
|
|
110
|
+
`,J=J.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":i.green("✓"),tag:B,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F$())console.error(J.trim());if(this.shouldWriteToFile())await this.writeToFile(J)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new rY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(F$())throw Error("createReadStream is not supported in browser environments");if(!zY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return tB(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=k0.isBuffer($)?$:k0.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=pH("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=k0.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F$()}isServerMode(){return!F$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
111
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:i.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:i.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:i.cyan(E),showTimestamp:!1}))}else if(!F$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
112
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(F$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();v.stdin.removeListener("data",A);try{if(typeof v.stdin.setRawMode==="function")v.stdin.setRawMode(!1)}catch{}v.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof v.stdin.setRawMode==="function")v.stdin.setRawMode(!0)}catch{}v.stdin.resume(),v.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${W}${U} ${i.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
113
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!v.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=i.green("━".repeat(Y)),U=i.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?i.green("✓"):i.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=v.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,v.stdout.write($.lastRenderedLine),w)v.stdout.write(`
|
|
114
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!v.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await hY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=f1(this.config.logDirectory,Y);if($.before)try{if((await Y1(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await HY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function H9($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class wU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return g8.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=GY.env[J]||(B?GY.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=GY.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof $U)throw j;throw W1.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw W1.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(GY.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
115
|
+
|
|
116
|
+
`;for(let Y of $)A+=`${Y.key}
|
|
117
|
+
`,A+=` Type: ${Y.type}
|
|
118
|
+
`,A+=` Description: ${Y.description}
|
|
119
|
+
`,A+=` Example: ${Y.example}
|
|
116
120
|
|
|
117
121
|
`;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
|
|
118
122
|
|
|
119
123
|
`;A+=`| Variable | Type | Description | Example |
|
|
120
124
|
`,A+=`|----------|------|-------------|----------|
|
|
121
|
-
`;for(let
|
|
122
|
-
`;return A}}function J2($,w,A={}){return EE($,w,A,new WeakMap)}function EE($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let W=f($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return FE($,w,U,J);if(!w0(w)||!w0($))return w;return Z2($,w,A,J)}function FE($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return U2($,w);case"smart":return Y2($,w,J);default:return w}return w}function U2($,w){let A=[...w];for(let J of $)if(!A.some((U)=>j8(U,J)))A.push(J);return A}function Y2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(w0(w[0])&&w0($[0]))return f2($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function f2($,w,A){let J=[...w];for(let U of $){if(!w0(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let W of Y)if(W in U){if(J.find((Z)=>w0(Z)&&(W in Z)&&Z[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function Z2($,w,A,J){let U=w;if(w0(U)&&J.has(U))return J.get(U);let Y={...$};if(w0(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let W=U[f],Z=Y[f];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){Y[f]=W;continue}if(w0(W)&&w0(Z))Y[f]=EE(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=FE(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function jE($,w,A="replace"){return J2($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function j8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!j8($[A],w[A]))return!1;return!0}if(w0($)&&w0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!j8($[U],w[U]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class zE{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:W=!1}=A;if(U){let B=zJ.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let Z=async()=>{if(!wJ($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),F=E.default||E,z="default"in E,j=Object.keys(E).length>0;if(!z&&!j)throw new RJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new RJ($,Error("Configuration must export a valid object"),"unknown");let G={config:jE(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)zJ.setWithFileCheck("file",G,$,Y);return G}catch(B){throw B instanceof Error?ow.configLoad($,B):ow.configLoad($,Error(String(B)))}};if(f)return G8.track("loadFromPath",Z,{path:$});return Z()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(rY(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let J=w===void 0?[]:Array.isArray(w)?w:[w];for(let Y of J){if(!Y)continue;if(A.push(Y,`.${Y}.config`,`${Y}.config`,`.${Y}`),$)A.push(`${$}.${Y}.config`,`.${$}.${Y}.config`)}let U=new Set;return A.filter((Y)=>{if(!Y||U.has(Y))return!1;return U.add(Y),!0})}checkFileAccess($){return A2(async()=>{return wJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!wJ($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=rY($,`${Y}${f}`);if(await this.checkFileAccess(W))J.push(W)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let W=rY($,f);if(await this.checkFileAccess(W))J.push(W)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!wJ($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class HE{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,B=async()=>{let E=[],F=[],z={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,z);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],z);else return this.validateWithJSONSchema($,w,z)}catch(j){return E.push({path:"",message:`Validation failed: ${j}`,rule:"system"}),{isValid:!1,errors:E,warnings:F}}};if(W)return await G8.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!nT(w))throw new MJ(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new MJ(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(f)){if(J.push({path:A,message:`Expected type ${W.join(" or ")}, got ${f}`,expected:W.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let W=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let W of w.required)if(!(W in f)){if(J.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[W,Z]of Object.entries(w.properties))if(W in f){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,B,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let Z of Object.keys(f))if(!W.has(Z))U.push({path:A?`${A}.${Z}`:Z,message:`Additional property '${Z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),W=this.validateWithRule(f,Y,Y.path);if(J.push(...W),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:W2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function B2($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class TE{fileLoader=new zE;envProcessor=new C8;validator=new HE;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let Z=this.checkCache(f.name||"",f);if(Z)return Z}let W;try{W=await this.loadConfigurationStrategies(f,!0,A)}catch(Z){let B=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(B)throw Z;W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(Z instanceof Error&&Z.name==="ConfigLoadError"){let E=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),F=!E&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),z=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(B&&(z||E))throw Z;if(F&&(!B||!z))W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Z.message}`]};else throw Z}else W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Z instanceof Error?Z.message:String(Z)}`]}}if(U||Y)await this.validateConfiguration(W.config,U,Y,f.name);if(A?.enabled&&W)this.cacheResult(f.name||"",W,A,f);if(J?.enabled){let Z={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(Z);if(J.slowThreshold&&Z.duration>J.slowThreshold)X0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let Z=Date.now()-w;throw X0.error(`Configuration loading failed after ${Z}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:W,checkEnv:Z=!0,arrayStrategy:B="replace",verbose:E=!1}=$,F=Y||CJ.cwd(),z=[],j=await this.loadLocalConfiguration(J,U,F,f,W,B,E,Z,A);if(j)return z.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(j,z,Z,J,E);let G=await this.loadHomeConfiguration(J,U,W,B,E,Z);if(G)return z.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(G,z,Z,J,E);let T=await this.loadPackageJsonConfiguration(J,U,F,W,B,E,Z);if(T)return z.push(e$(F,"package.json")),this.finalizeResult(T,z,Z,J,E);if(z.push(...this.getAllSearchPaths(J,U,F,f)),w)throw ow.configNotFound(J,z,U);return{...await this.applyEnvironmentVariables(J,W,Z,E),warnings:[`No configuration file found for "${J}"${B2(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let B=W?JJ($,U,f):U,E=this.getLocalDirectories(A,J);for(let F of E){if(f)X0.info(`Searching for configuration in: ${F}`);let z=this.fileLoader.generateConfigPaths($,F,w),j=await this.fileLoader.tryLoadFromPaths(z,B,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(j){if(f)X0.success(`Configuration loaded from: ${j.source.path}`);return j}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?JJ($,A,U):A,W=[e$(cw(),".config",$),e$(cw(),".config"),cw()];for(let Z of W){if(U)X0.info(`Checking home directory: ${Z}`);let B=this.fileLoader.generateConfigPaths($,Z,w),E=await this.fileLoader.tryLoadFromPaths(B,f,{arrayStrategy:J,verbose:U});if(E){if(U)X0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?JJ($,J,Y):J;try{let Z=e$(A,"package.json");if(!AT(Z))return null;let B={};try{B=JSON.parse(JT(Z,"utf8"))}catch(z){if(Y)X0.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let E=B[$],F=$;if(!E&&w){let z=Array.isArray(w)?w:[w];for(let j of z){if(!j)continue;if(B[j]){E=B[j],F=j;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(Y)X0.success(`Configuration loaded from package.json: ${F}`);return{config:jE(W,E,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)X0.warn("Failed to load package.json:",[Z instanceof Error?Z:Error(String(Z))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:JJ($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw ow.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return zJ.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);zJ.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let J=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${J}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,e$($,"config"),e$($,".config"),w?e$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(e$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[e$(cw(),".config",$),e$(cw(),".config"),cw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function JJ($,w,A=!1){let J=new C8,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],j,G;for(let T of z)if(j=CJ.env[T],j!==void 0){G=T;break}if(j!==void 0&&G)if(typeof E==="boolean")Z[B]=["true","1","yes"].includes(j.toLowerCase());else if(typeof E==="number"){let T=Number(j);if(!Number.isNaN(T))Z[B]=T}else if(Array.isArray(E))try{Z[B]=JSON.parse(j)}catch{Z[B]=j.split(",").map((T)=>T.trim())}else Z[B]=j;else if(E&&typeof E==="object"&&!Array.isArray(E))Z[B]=Y(E,F)}return Z}return Y(w)}function z8($,w){let A=[];function J(U){let Y;try{Y=VB.readdirSync(U)}catch{return}for(let f of Y){let W=B0.join(U,f);try{if(VB.statSync(W).isDirectory())J(W);else if(f===w)A.push(U)}catch{continue}}}return J($),A}function M($,w,A){if(A||U$.verbose)console.debug(`[tlsx:${$}] ${w}`)}function qE(){return hE.env.SUDO_PASSWORD}function G2($){let w=$.toLowerCase();return H2.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function IJ($){if(Array.isArray($))return $.map((A)=>IJ(A));if(typeof $==="string")return T2.test($)?OB:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(G2(A)){w[A]=OB;continue}w[A]=IJ(J)}return w}function OJ($){return JSON.stringify(IJ($))}function h2($){let w=qE();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),J=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${J}`}async function s0($,w={}){let A=h2($);try{let{stdout:J,stderr:U}=await z2(A,{cwd:w.cwd||hE.cwd(),timeout:w.timeout||30000});return{stdout:J.trim(),stderr:U.trim()}}catch(J){let U=Error(`Failed to execute command: ${$}
|
|
123
|
-
Error: ${
|
|
124
|
-
${
|
|
125
|
+
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
126
|
+
`;return A}}function G9($,w,A={}){return Wj($,w,A,new WeakMap)}function Wj($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return Bj($,w,f,Y);if(!X0(w)||!X0($))return w;return N9($,w,A,Y)}function Bj($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return K9($,w);case"smart":return R9($,w,Y);default:return w}return w}function K9($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>n8(f,Y)))A.push(Y);return A}function R9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(X0(w[0])&&X0($[0]))return q9($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function q9($,w,A){let Y=[...w];for(let f of $){if(!X0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>X0(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function N9($,w,A,Y){let f=w;if(X0(f)&&Y.has(f))return Y.get(f);let X={...$};if(X0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(X0(W)&&X0(J))X[U]=Wj(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=Bj(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function Ej($,w,A="replace"){return G9($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function n8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!n8($[A],w[A]))return!1;return!0}if(X0($)&&X0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!n8($[f],w[f]))return!1}return!0}return!1}function X0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class jj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=kY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!KY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new nY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new nY($,Error("Configuration must export a valid object"),"unknown");let H={config:Ej(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)kY.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?W1.configLoad($,B):W1.configLoad($,Error(String(B)))}};if(U)return g8.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(q8(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return H9(async()=>{return KY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!KY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=q8($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=q8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!KY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class Tj{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await g8.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!AG(w))throw new vY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new vY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:y9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function M9($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class Fj{fileLoader=new jj;envProcessor=new wU;validator=new Tj;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)Z0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw Z0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||gY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let h=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(h)return T.push(Y0(j,"package.json")),this.finalizeResult(h,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw W1.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${M9(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?qY($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)Z0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)Z0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?qY($,A,f):A,W=[Y0(rw(),".config",$),Y0(rw(),".config"),rw()];for(let J of W){if(f)Z0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)Z0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?qY($,Y,X):Y;try{let J=Y0(A,"package.json");if(!HH(J))return null;let B={};try{B=JSON.parse(GH(J,"utf8"))}catch(T){if(X)Z0.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)Z0.success(`Configuration loaded from package.json: ${j}`);return{config:Ej(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)Z0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:qY($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw W1.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return kY.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);kY.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Y0($,"config"),Y0($,".config"),w?Y0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(Y0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[Y0(rw(),".config",$),Y0(rw(),".config"),rw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function qY($,w,A=!1){let Y=new wU,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((h)=>h.toUpperCase()).join("")}`,`${f}_${j.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let h of T)if(F=gY.env[h],F!==void 0){H=h;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let h=Number(F);if(!Number.isNaN(h))J[B]=h}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((h)=>h.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function v8($,w){let A=[];function Y(f){let X;try{X=TE.readdirSync(f)}catch{return}for(let U of X){let W=h0.join(f,U);try{if(TE.statSync(W).isDirectory())Y(W);else if(U===w)A.push(f)}catch{continue}}}return Y($),A}function I($,w,A){if(A||J$.verbose)console.debug(`[tlsx:${$}] ${w}`)}function Hj(){return hj.env.SUDO_PASSWORD}function Q9($){let w=$.toLowerCase();return O9.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function mY($){if(Array.isArray($))return $.map((A)=>mY(A));if(typeof $==="string")return V9.test($)?FE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(Q9(A)){w[A]=FE;continue}w[A]=mY(Y)}return w}function aY($){return JSON.stringify(mY($))}function _9($){let w=Hj();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),Y=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${Y}`}async function Aw($,w={}){let A=_9($);try{let{stdout:Y,stderr:f}=await L9(A,{cwd:w.cwd||hj.cwd(),timeout:w.timeout||30000});return{stdout:Y.trim(),stderr:f.trim()}}catch(Y){let f=Error(`Failed to execute command: ${$}
|
|
127
|
+
Error: ${Y.message}`);throw f.stack=Y.stack,f}}function Gj($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function AU($){let w=h0.join(C9.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:J$.basePath&&J$.basePath.trim()!==""?J$.basePath:w,Y=$.certPath?h0.isAbsolute($.certPath)?$.certPath:h0.join(A,$.certPath):h0.join(A,J$.certPath),f=$.keyPath?h0.isAbsolute($.keyPath)?$.keyPath:h0.join(A,$.keyPath):h0.join(A,J$.keyPath),X=$.caCertPath?h0.isAbsolute($.caCertPath)?$.caCertPath:h0.join(A,$.caCertPath):h0.join(A,J$.caCertPath);return{certPath:Y,keyPath:f,caCertPath:X,basePath:A}}function Kj($){let w=[],A=new Set;if($.domain)A.add($.domain);if($.domains?.length)$.domains.forEach((Y)=>A.add(Y));for(let Y of A)w.push({type:2,value:Y});if($.altNameIPs?.length)for(let Y of $.altNameIPs)w.push({type:7,ip:Y});if($.altNameURIs?.length)for(let Y of $.altNameURIs)w.push({type:6,value:Y});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return I(C.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function YU($){let w=$.notBeforeDays??G0.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:G0.DEFAULT_VALIDITY_DAYS);I(C.CERT,"Calculating certificate validity dates",$.verbose);let Y=new Date(Date.now()-86400*w*1000),f=new Date(Y.getTime()+A*24*60*60*1000);return Y.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),I(C.CERT,`Validity period: ${Y.toISOString()} to ${f.toISOString()}`,$.verbose),{notBefore:Y,notAfter:f}}function u1($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function s$($,w){let A=u1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function l1($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let Y=2;Y<w.length;Y++){let f=w[Y],X=[];X.unshift(f&127),f>>=7;while(f>0)X.unshift(f&127|128),f>>=7;A.push(...X)}return s$(K0.OID,Buffer.from(A))}function m8($){let w;if(typeof $==="bigint"){let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return s$(K0.INTEGER,w)}function Rj($,w=0){return s$(K0.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function qj($){return s$(K0.OCTET_STRING,$)}function a$(...$){return s$(K0.SEQUENCE,Buffer.concat($))}function D9(...$){return s$(K0.SET,Buffer.concat($))}function k9($){return s$(K0.PRINTABLE_STRING,Buffer.from($,"ascii"))}function Z9($){return s$(K0.UTF8_STRING,Buffer.from($,"utf8"))}function x9(){return Buffer.from([K0.NULL,0])}function zE($,w,A=!0){let Y=160|$|(A?0:0),f=u1(w.length);return Buffer.concat([Buffer.from([Y]),f,w])}function hE($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return s$(K0.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),Y=($.getUTCMonth()+1).toString().padStart(2,"0"),f=$.getUTCDate().toString().padStart(2,"0"),X=$.getUTCHours().toString().padStart(2,"0"),U=$.getUTCMinutes().toString().padStart(2,"0"),W=$.getUTCSeconds().toString().padStart(2,"0"),J=`${A}${Y}${f}${X}${U}${W}Z`;return s$(K0.UTC_TIME,Buffer.from(J,"ascii"))}}function P9($,w){return a$(hE($),hE(w))}function HE($){let w=[];for(let A of $){let Y;switch(A.shortName){case"CN":Y=i$.COMMON_NAME;break;case"C":Y=i$.COUNTRY;break;case"L":Y=i$.LOCALITY;break;case"ST":Y=i$.STATE;break;case"O":Y=i$.ORGANIZATION;break;case"OU":Y=i$.ORGANIZATIONAL_UNIT;break;default:continue}let f=A.shortName==="C"?k9(A.value):Z9(A.value),X=a$(l1(Y),f);w.push(D9(X))}return a$(...w)}function Nj($){return a$(l1($),x9())}function i9($){return $.export({type:"spki",format:"der"})}function b9($){if($.includes(":")){let w=$;if($.includes("::")){let f=$.split("::"),X=f[0]?f[0].split(":"):[],U=f[1]?f[1].split(":"):[],W=8-X.length-U.length,J=Array.from({length:W},()=>"0");w=[...X,...J,...U].join(":")}let A=w.split(":"),Y=Buffer.alloc(16);for(let f=0;f<8;f++){let X=Number.parseInt(A[f]||"0",16);Y.writeUInt16BE(X,f*2)}return Y}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function c9($){let w=[];for(let A of $)if(A.type===2&&A.value){let Y=u1(A.value.length);w.push(Buffer.concat([Buffer.from([130]),Y,Buffer.from(A.value,"ascii")]))}else if(A.type===7&&A.ip){let Y=b9(A.ip),f=u1(Y.length);w.push(Buffer.concat([Buffer.from([135]),f,Y]))}else if(A.type===6&&A.value){let Y=u1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),Y,Buffer.from(A.value,"ascii")]))}return a$(...w)}function u9($,w){if($){if(w!==void 0)return a$(s$(1,Buffer.from([255])),m8(w));return a$(s$(1,Buffer.from([255])))}return a$()}function n9($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let A=0,Y=w;while(Y>0&&(Y&1)===0)A++,Y>>=1;if(w===0)A=7;return Rj(Buffer.from([w]),A)}function v9($){let w=[];if($.serverAuth)w.push(l1(i$.SERVER_AUTH));if($.clientAuth)w.push(l1(i$.CLIENT_AUTH));return a$(...w)}function b1($,w,A){let Y=[l1($)];if(w)Y.push(s$(1,Buffer.from([255])));return Y.push(qj(A)),a$(...Y)}function m9($){let w=[];if(w.push(zE(0,m8(2))),w.push(m8($.serialNumber)),w.push(Nj(i$.SHA256_WITH_RSA)),w.push(HE($.issuer)),w.push(P9($.notBefore,$.notAfter)),w.push(HE($.subject)),w.push(i9($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(b1(i$.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,u9($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(b1(i$.KEY_USAGE,$.extensions.keyUsage.critical??!0,n9($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(b1(i$.EXTENDED_KEY_USAGE,!1,v9($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(b1(i$.SUBJECT_ALT_NAME,!1,c9($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(b1(i$.SUBJECT_KEY_IDENTIFIER,!1,qj($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push(zE(3,a$(...A)))}return a$(...w)}function d9($,w){let A=B1.createSign("SHA256");A.update($);let Y=A.sign(w);return a$($,Nj(i$.SHA256_WITH_RSA),Rj(Y))}function l9($,w){let A=$.toString("base64"),Y=[];for(let f=0;f<A.length;f+=64)Y.push(A.slice(f,f+64));return`-----BEGIN ${w}-----
|
|
128
|
+
${Y.join(`
|
|
125
129
|
`)}
|
|
126
130
|
-----END ${w}-----
|
|
127
|
-
`}function
|
|
128
|
-
`);for(let Y of U){let[f,...W]=Y.split("="),Z=W.join("=");if(f&&Z)J.push({shortName:f.trim(),value:Z.trim()})}return{publicKey:A,subject:J}}async function O8($={}){M("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||F0.DEFAULT_KEY_SIZE;M("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=yE(w),U=[{shortName:"C",value:$.countryName||U$.countryName},{shortName:"ST",value:$.stateName||U$.stateName},{shortName:"L",value:$.localityName||U$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:Y,notAfter:f}=S8({validityYears:$.validityYears||F0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=CE({serialNumber:V8(),notBefore:Y,notAfter:f,subject:U,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:LE(A),notBefore:Y,notAfter:f}}async function X8($){if(M("ca","Generating new certificate",$.verbose),M("ca",`Options: ${OJ($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=Q2($.rootCA.certificate),A=k2($.rootCA.privateKey);M("ca",`Generating ${F0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=F0.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:Y}=yE(J),f=$.commonName||NE($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||U$.countryName},{shortName:"ST",value:$.stateName||U$.stateName},{shortName:"L",value:$.localityName||U$.localityName},{shortName:"O",value:$.organizationName||U$.organizationName},{shortName:"CN",value:f}],{notBefore:Z,notAfter:B}=S8({validityDays:$.validityDays||F0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),E=KE($),F=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},z=$.extKeyUsage||{serverAuth:!0},{certificate:j}=CE({serialNumber:V8(),notBefore:Z,notAfter:B,subject:W,issuer:w,publicKey:Y,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:F,extendedKeyUsage:z,subjectAltName:E});return{certificate:j,privateKey:LE(U),notBefore:Z,notAfter:B}}function SE($,w){M(I.STORAGE,`Storing certificate and private key with options: ${OJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=L8({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});M(I.STORAGE,`Certificate path: ${A}`,w?.verbose),M(I.STORAGE,`Private key path: ${J}`,w?.verbose);let U=T8.dirname(A);if(!Q0.existsSync(U))M(I.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),Q0.mkdirSync(U,{recursive:!0});M(I.STORAGE,"Writing certificate file",w?.verbose),Q0.writeFileSync(A,$.certificate);let Y=T8.dirname(J);if(!Q0.existsSync(Y))M(I.STORAGE,`Creating private key directory: ${Y}`,w?.verbose),Q0.mkdirSync(Y,{recursive:!0});return M(I.STORAGE,"Writing private key file",w?.verbose),Q0.writeFileSync(J,$.privateKey),M(I.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function VE($,w){M(I.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=L8({basePath:w?.basePath,caCertPath:w?.caCertPath});M(I.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=T8.dirname(A);if(!Q0.existsSync(J))M(I.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),Q0.mkdirSync(J,{recursive:!0});return M(I.STORAGE,"Writing CA certificate file",w?.verbose),Q0.writeFileSync(A,$),M(I.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function x2($,w){if(yJ.platform()!=="darwin")return!1;try{let A=kB(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return M(I.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(kB("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return M(I.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return M(I.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return M(I.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function _8($,w,A){M(I.TRUST,`Adding certificate to system trust store with options: ${OJ(A)}`,A?.verbose),M(I.TRUST,"Storing certificate and private key",A?.verbose);let J=SE($,A);M(I.TRUST,"Storing CA certificate",A?.verbose);let U=VE(w,A),Y=yJ.platform();M(I.TRUST,`Detected platform: ${Y}`,A?.verbose);let f=c2[Y];if(!f){let W=`Unsupported platform: ${Y}`;throw M(I.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await f.addCertificate(U,A),M(I.TRUST,"Certificate successfully added to system trust store",A?.verbose),J}var DN,zJ,G8,mT,dT=($)=>$,lT=($,w)=>{for(var A in w)mT($,A,{get:w[A],enumerable:!0,configurable:!0,set:gT.bind(w,A)})},pT=($,w)=>()=>($&&(w=$($=0)),w),iB,pB,sw,Q1,tB,KG,RG,GB,YJ,U8,I$,l,MG,hB,IG,qB,yG,CG,aY,LG,NB,KB,sY,SG,VG,OG,XG,fJ,rB,_G,y$,DG,kG,RB,ZJ,Y8,E$,k,QG,MB,xG,IB,PG,bG,oY,iG,yB,CB,cG,eY,uG,vG,nG,mG,dG,WJ,aB,gG,lG="0.15.6",l$,qJ,_1,f8,Z8,NJ,W8,B8,D1,E8,F8,o0,sB,oB,E0,x0,eB,$E,pG,rG,wE,KJ,JR,h$,b,UR,sG,YR,oG,fR,ZR,LB,WR,eG,$2,BR,SB,ER,FR,jR,zR,HR,$8,w2,TR,z0,JE,RJ,UE,YE,y8,fE,ZE,MJ,WE,BE,ow,W2,X0,GR,hR,qR,GE,U$,F0,I,aw,z2,OB="[redacted]",H2,T2,j0,x$,P2,b2,i2,c2;var OE=X$(()=>{DN=wT(import.meta.url);zJ=new PB,G8=new bB,mT=Object.defineProperty;iB={};lT(iB,{withErrorRecovery:()=>vB,tryLoadConfig:()=>GG,loadConfigWithResult:()=>HG,loadConfig:()=>lB,isRetryableError:()=>WG,isConfigNotFoundError:()=>ZG,isBunfigError:()=>nB,globalPerformanceMonitor:()=>Q1,globalCache:()=>sw,getEnvOrDefault:()=>BG,generateConfigTypes:()=>hG,defaultGeneratedDir:()=>$E,defaultConfigDir:()=>eB,deepMergeWithArrayStrategy:()=>R8,deepMerge:()=>mB,createLibraryConfig:()=>qG,config:()=>TG,bunfigPlugin:()=>NG,applyEnvVarsToConfig:()=>V1,TypeGenerationError:()=>B8,SchemaValidationError:()=>D1,PluginError:()=>F8,PerformanceMonitor:()=>q8,FileSystemError:()=>W8,ErrorFactory:()=>o0,EnvVarError:()=>NJ,EnvProcessor:()=>LJ,ConfigValidator:()=>M8,ConfigValidationError:()=>f8,ConfigNotFoundError:()=>qJ,ConfigMergeError:()=>Z8,ConfigLoader:()=>I8,ConfigLoadError:()=>_1,ConfigFileLoader:()=>SJ,ConfigCache:()=>h8,CacheUtils:()=>tB,BunfigError:()=>l$,BrowserConfigError:()=>E8,ArrayMergeStrategies:()=>sB});pG=pT(async()=>{pB=import.meta.require,sw=new h8,Q1=new q8,tB={createKey:tT,isEquivalent:rT,estimateMemoryUsage:aT},KG=FJ(A8.cwd(),"config"),RG=FJ(A8.cwd(),"src/generated"),GB=EJ.env.CLARITY_LOG_DIR||BT(eT(),"logs"),YJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:GB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},U8=await $G(),I$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},l=I$,MG=I$.red,hB=I$.green,IG=I$.yellow,qB=I$.blue,yG=I$.magenta,CG=I$.cyan,aY=I$.white,LG=I$.gray,NB=I$.bgRed,KB=I$.bgYellow,sY=I$.bold,SG=I$.dim,VG=I$.italic,OG=I$.underline,XG=I$.reset,fJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rB={debug:"\uD83D\uDD0D",info:qB("ℹ"),success:hB("✓"),warning:KB(aY(sY(" WARN "))),error:NB(aY(sY(" ERROR ")))},_G=new TJ("stacks"),y$=new TJ("bunfig",{showTags:!0}),DG=k$(X1.cwd(),"config"),kG=k$(X1.cwd(),"src/generated"),RB=BJ.env.CLARITY_LOG_DIR||ZT(UG(),"logs"),ZJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:RB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Y8=await YG(),E$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},k=E$,QG=E$.red,MB=E$.green,xG=E$.yellow,IB=E$.blue,PG=E$.magenta,bG=E$.cyan,oY=E$.white,iG=E$.gray,yB=E$.bgRed,CB=E$.bgYellow,cG=E$.bgGray,eY=E$.bold,uG=E$.dim,vG=E$.italic,nG=E$.underline,mG=E$.strikethrough,dG=E$.reset,WJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},aB={debug:"\uD83D\uDD0D",info:IB("ℹ"),success:MB("✓"),warning:CB(oY(eY(" WARN "))),error:yB(oY(eY(" ERROR ")))},gG=new hJ("stacks"),l$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},qJ=class extends l${code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A?` or alias "${A}"`:"";super(`Configuration "${$}"${J} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},_1=class extends l${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},f8=class extends l${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},Z8=class extends l${code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},NJ=class extends l${code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}},W8=class extends l${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},B8=class extends l${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},D1=class extends l${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},E8=class extends l${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},F8=class extends l${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},o0={configNotFound($,w,A){return new qJ($,w,A)},configLoad($,w,A){return new _1($,w,A)},configValidation($,w,A){return new f8($,w,A)},configMerge($,w,A,J){return new Z8($,w,A,J)},envVar($,w,A,J){return new NJ($,w,A,J)},fileSystem($,w,A){return new W8($,w,A)},typeGeneration($,w,A){return new B8($,w,A)},schemaValidation($,w,A){return new D1($,w,A)},browserConfig($,w,A,J){return new E8($,w,A,J)},plugin($,w,A){return new F8($,w,A)}},sB={replace:"replace",concat:"concat",smart:"smart"},oB=/^https?:\/\//,E0=new hJ("bunfig",{showTags:!0}),x0=new I8,eB=Q$(Fw.cwd(),"config"),$E=Q$(Fw.cwd(),"src/generated")});rG=jJ.env.CLARITY_LOG_DIR||_T(tG(),"logs"),wE={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},KJ={...wE},JR=(async()=>{try{let{loadConfig:$}=await pG().then(()=>iB),w=await $({name:"clarity",alias:"logging",defaultConfig:wE,cwd:jJ.cwd()});if(w)Object.assign(KJ,w)}catch{}return KJ})();h$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=h$,UR=h$.red,sG=h$.green,YR=h$.yellow,oG=h$.blue,fR=h$.magenta,ZR=h$.cyan,LB=h$.white,WR=h$.gray,eG=h$.bgRed,$2=h$.bgYellow,BR=h$.bgGray,SB=h$.bold,ER=h$.dim,FR=h$.italic,jR=h$.underline,zR=h$.strikethrough,HR=h$.reset,$8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},w2={debug:"\uD83D\uDD0D",info:oG("ℹ"),success:sG("✓"),warning:$2(LB(SB(" WARN "))),error:eG(LB(SB(" ERROR ")))};TR=new VJ("stacks");z0=class z0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};JE=class JE extends z0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],U="";if(J.length===1)U=` or alias "${J[0]}"`;else if(J.length>1)U=` or aliases ${J.map((Y)=>`"${Y}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};RJ=class RJ extends z0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};UE=class UE extends z0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};YE=class YE extends z0{code="CONFIG_MERGE_ERROR";constructor($,w,A,J){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}};y8=class y8 extends z0{code="ENV_VAR_ERROR";constructor($,w,A,J){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:J})}};fE=class fE extends z0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};ZE=class ZE extends z0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};MJ=class MJ extends z0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};WE=class WE extends z0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}};BE=class BE extends z0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};ow={configNotFound($,w,A){return new JE($,w,A)},configLoad($,w,A){return new RJ($,w,A)},configValidation($,w,A){return new UE($,w,A)},configMerge($,w,A,J){return new YE($,w,A,J)},envVar($,w,A,J){return new y8($,w,A,J)},fileSystem($,w,A){return new fE($,w,A)},typeGeneration($,w,A){return new ZE($,w,A)},schemaValidation($,w,A){return new MJ($,w,A)},browserConfig($,w,A,J){return new WE($,w,A,J)},plugin($,w,A){return new BE($,w,A)}};W2=/^https?:\/\//;X0=new VJ("bunfig",{showTags:!0});GR=new TE;hR=e$(CJ.cwd(),"config"),qR=e$(CJ.cwd(),"src/generated"),GE={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:xY.join(QY.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:xY.join(QY.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:xY.join(QY.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},U$=GE,F0={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"},I={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},aw={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};z2=j2(E2);H2=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),T2=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;j0={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},x$={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"};P2={platform:"darwin",async addCertificate($,w){if(await x2($,w?.verbose)){M(I.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),aw.success("Certificate is already trusted in system keychain");return}M(I.TRUST,"Adding certificate to macOS keychain",w?.verbose),await s0(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||U$.commonName;M(I.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await s0(`sudo security delete-certificate -c "${J}" /Library/Keychains/System.keychain`),M(I.TRUST,`Removed certificate ${J} from macOS keychain`,w?.verbose)}catch(U){throw M(I.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},b2={platform:"win32",async addCertificate($,w){M(I.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await s0(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||U$.commonName;M(I.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await s0(`certutil -delstore -enterprise Root "${J}"`),M(I.TRUST,`Removed certificate ${J} from Windows certificate store`,w?.verbose)}catch(U){throw M(I.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},i2={platform:"linux",async addCertificate($,w){M(I.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=yJ.homedir(),J=F0.LINUX_CERT_DB_FILENAME,U=F0.LINUX_TRUST_ARGS;M(I.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let Y=z8(A,J);if(Y.length===0){aw.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let f of Y){M(I.TRUST,`Processing certificate database in ${f}`,w?.verbose);try{M(I.TRUST,`Attempting to delete existing cert for ${U$.commonName}`,w?.verbose),await s0(`certutil -d sql:${f} -D -n ${U$.commonName}`)}catch(W){M(I.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}M(I.TRUST,`Adding new certificate to ${f}`,w?.verbose),await s0(`certutil -d sql:${f} -A -t ${U} -n ${U$.commonName} -i ${$}`),aw.info(`Cert added to ${f}`)}},async removeCertificate($,w,A){let J=A||U$.commonName;M(I.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let U=yJ.homedir(),Y=F0.LINUX_CERT_DB_FILENAME;M(I.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let f=z8(U,Y);if(f.length===0){aw.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of f){M(I.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await s0(`certutil -d sql:${W} -D -n "${J}"`),aw.info(`Cert removed from ${W}`)}catch(Z){M(I.TRUST,`Error removing cert from ${W}: ${Z}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${Z}`)}}}},c2={darwin:P2,win32:b2,linux:i2}});var XE=X$(()=>{OE()});import{homedir as D8}from"node:os";import{join as k8,resolve as ZM}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",u2,Q8;var x8=X$(()=>{_Y();u2={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:k8(D8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:k8(D8(),".stacks","ssl","stacks.localhost.crt"),keyPath:k8(D8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},Q8=u2});import{execSync as v2}from"node:child_process";function _E($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function XJ($){try{let w=v2(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return _E(w)}catch{return null}}var P8=()=>{};import{existsSync as DE,statSync as kE}from"fs";import{existsSync as wf,mkdirSync as p2,readdirSync as t2,writeFileSync as r2}from"fs";import{homedir as $1}from"os";import{dirname as QE,resolve as b$}from"path";import jw from"process";import{join as a2,relative as s2,resolve as xE}from"path";import pJ from"process";import{existsSync as hF,mkdirSync as KM,readdirSync as RM,writeFileSync as MM}from"fs";import{homedir as b8}from"os";import{dirname as CM,resolve as P$}from"path";import P1 from"process";import{join as o2,relative as e2,resolve as PE}from"path";import tJ from"process";import{existsSync as qF,mkdirSync as XM,readdirSync as _M,writeFileSync as DM}from"fs";import{dirname as QM,resolve as rJ}from"path";import Af from"process";import{Buffer as e0}from"buffer";import{createCipheriv as $h,createDecipheriv as wh,randomBytes as i8}from"crypto";import{closeSync as c8,createReadStream as bE,createWriteStream as Ah,existsSync as u8,fsyncSync as iE,openSync as cE,writeFileSync as Jh}from"fs";import{access as Uh,constants as uE,mkdir as Yh,readdir as _J,rename as vE,stat as w1,unlink as DJ,writeFile as v8}from"fs/promises";import{join as A1}from"path";import C$ from"process";import{pipeline as fh}from"stream/promises";import{createGzip as nE}from"zlib";import J1 from"process";import i0 from"process";import{Buffer as P0}from"buffer";import{createCipheriv as Zh,createDecipheriv as Wh,randomBytes as n8}from"crypto";import{closeSync as m8,createReadStream as mE,createWriteStream as Bh,existsSync as kJ,fsyncSync as dE,openSync as gE,writeFileSync as Eh}from"fs";import{access as Fh,constants as lE,mkdir as jh,readdir as QJ,rename as pE,stat as U1,unlink as xJ,writeFile as d8}from"fs/promises";import{isAbsolute as zh,join as Y1,resolve as Hh}from"path";import X from"process";import{pipeline as Th}from"stream/promises";import{createGzip as tE}from"zlib";import f1 from"process";import c0 from"process";import PJ from"process";import{existsSync as bJ}from"fs";import{resolve as g8}from"path";import{existsSync as Gh}from"fs";import{existsSync as hh,readdirSync as qh}from"fs";import{extname as l8,resolve as rE}from"path";import Nh from"process";import{join as K7,relative as R7,resolve as ZF}from"path";import AU from"process";import{Buffer as b0}from"buffer";import{createCipheriv as y7,createDecipheriv as C7,randomBytes as s8}from"crypto";import{closeSync as o8,createReadStream as WF,createWriteStream as L7,existsSync as cJ,fsyncSync as BF,openSync as EF,writeFileSync as S7}from"fs";import{access as V7,constants as FF,mkdir as O7,readdir as uJ,rename as jF,stat as Z1,unlink as vJ,writeFile as e8}from"fs/promises";import{isAbsolute as X7,join as W1,resolve as _7}from"path";import _ from"process";import{pipeline as D7}from"stream/promises";import{createGzip as zF}from"zlib";import B1 from"process";import u0 from"process";function d2($,w){this[$]=m2.bind(null,w)}class jf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,J])=>A.timestamp.getTime()-J.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,J){if(!this.options.enabled)return;let U=this.generateKey($,A),Y=J??this.options.ttl,f=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:Y,hits:0,size:f}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),J=this.cache.get(A);if(!J){this.totalMisses++;return}if(this.isExpired(J)){this.cache.delete(A),this.totalMisses++;return}return J.hits++,this.totalHits++,J.value}isFileModified($,w){try{if(!DE($))return!0;return kE($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,J){try{let U=DE(A)?kE(A):null,Y=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:Y},A,J)}catch{this.set($,w,A,J)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((J,U)=>J+U.size,0),A=$.map((J)=>J.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let J=A;this.cache.set(w,{value:J.value,timestamp:new Date(J.timestamp),ttl:J.ttl,hits:J.hits,size:J.size})}}}class zf{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),U=new Date;try{let Y=await w(),f=performance.now()-J;return this.recordMetric({operation:$,duration:f,timestamp:U,...A}),Y}catch(Y){let f=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:f,timestamp:U,...A}),Y}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((U)=>U.duration),J=A.reduce((U,Y)=>U+Y,0);return{count:w.length,averageDuration:J/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:J,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function Kh($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function Rh($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function Mh($){return $.getStats().size*2}function Hf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&s(w[0])&&"id"in w[0]&&w[0].id===3&&s(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(s(w)&&s($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(s($)&&"arr"in $&&Array.isArray($.arr)&&s(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&s(w[0])&&s($[0])){let J=[...w];for(let U of $)if(s(U)&&"name"in U){if(!J.find((f)=>s(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(s(U)&&"path"in U){if(!J.find((f)=>s(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>aJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!s(w)||!s($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(s(U)&&s(A[J]))A[J]=Hf(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&s(U[0])&&s(A[J][0])){let Y=[...U];for(let f of A[J])if(s(f)&&"name"in f){if(!Y.find((Z)=>s(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(s(f)&&"path"in f){if(!Y.find((Z)=>s(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>aJ(W,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function aJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aJ($[A],w[A]))return!1;return!0}if(s($)&&s(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!aJ($[U],w[U]))return!1}return!0}return!1}function s($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Ih($,w){if(!qF($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return Hf(w,J)}catch{return null}}catch{return null}}async function yh({name:$="",cwd:w,defaultConfig:A}){let J=w||Af.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=rJ(J,`${f}${W}`),B=await Ih(Z,A);if(B!==null)return B}try{let f=rJ(J,"package.json");if(qF(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return Hf(A,Z)}catch{}}}catch{}return A}function Ch($,w={}){let A=tJ.cwd();while(A.includes("storage"))A=PE(A,"..");let J=PE(A,$||"");if(w?.relative)return e2(tJ.cwd(),J);return J}async function Lh(){try{let $=await yh({name:"clarity",defaultConfig:mJ,cwd:tJ.cwd(),endpoint:"",headers:{}});return{...mJ,...$}}catch{return mJ}}function A$(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Sh(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i0<"u"){let $=i0.type;if($==="renderer"||$==="worker")return!1;return!!(i0.versions&&(i0.versions.node||i0.versions.bun))}return!1}class NF{async format($){let w=await Sh(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:J1.pid,hostname:w(),environment:J1.env.NODE_ENV||"development",platform:J1.platform,version:J1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:J1.env.NODE_ENV||J1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Uf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new NF,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??C$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...dJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...dJ};return{...dJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Uf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await Uh(this.config.logDirectory,uE.F_OK|uE.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Yh(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:e0.from($);try{if(!u8(this.currentLogFile))await v8(this.currentLogFile,"",{mode:420});if(U=cE(this.currentLogFile,"a",420),Jh(U,Z,{flag:"a"}),iE(U),U!==void 0)c8(U),U=void 0;if((await w1(this.currentLogFile)).size===0){if(await v8(this.currentLogFile,Z,{flag:"w",mode:420}),(await w1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<f-1){let F=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let z=W*2**Y;await new Promise((j)=>setTimeout(j,z)),Y++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{c8(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Z){if(Y===f-1){let E=Z,F=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),Z}Y++;let B=W*2**(Y-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return A1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return A1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(A$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Z])=>Z.createdAt.getTime()-W.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[W]of U.slice(f))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return i8(16).toString("hex")}generateKey(){return i8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=i8(16),J=$h("aes-256-gcm",w,A),U=e0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:e0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=nE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(e0.from(e0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(A$())return;let $=await w1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await _J(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await w1(A).catch(()=>null))try{if(await vE(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await DJ(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await v8(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await w1(A).catch(()=>null))await vE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await _J(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await DJ(A1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=bE($),J=Ah(w),U=nE();await fh(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);await this.writeToFile(J),console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),u8(this.currentLogFile))try{let $=cE(this.currentLogFile,"r+");iE($),c8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!A$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await _J(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await DJ(A1(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?p.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=C$.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${p.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);if(this.fancy&&!A$()){let B=OF[$],E=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:p.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:p.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:B,tag:E,message:f,level:$}),console.error(F),W){let z=W.split(`
|
|
129
|
-
`);for(let
|
|
130
|
-
`;if(W)
|
|
131
|
-
`;
|
|
132
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
133
|
-
`),
|
|
134
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
135
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
136
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||A$()||!C$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(A$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await _J(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=A1(this.config.logDirectory,J);if($.before)try{if((await w1(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await DJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function nJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let J=[...w];for(let U of $)if(d(U)&&"name"in U){if(!J.find((f)=>d(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((f)=>d(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>oJ(Y,U)))J.push(U);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}if(!d(w)||!d($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let U=w[J];if(U===null||U===void 0)continue;else if(d(U)&&d(A[J]))A[J]=nJ(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&d(U[0])&&d(A[J][0])){let Y=[...U];for(let f of A[J])if(d(f)&&"name"in f){if(!Y.find((Z)=>d(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(d(f)&&"path"in f){if(!Y.find((Z)=>d(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>oJ(W,f)))Y.push(f);A[J]=Y}else if(U.every((Y)=>typeof Y==="string")&&A[J].every((Y)=>typeof Y==="string")){let Y=[...U];for(let f of A[J])if(!Y.includes(f))Y.push(f);A[J]=Y}else A[J]=U;else A[J]=U}return A}function Tf($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:nJ($,w);if(Array.isArray($))return A==="replace"?w:nJ($,w);if(!d(w)||!d($))return w;let J={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let Y=w[U],f=J[U];if(Y===null||Y===void 0)continue;if(Array.isArray(Y)||Array.isArray(f))if(A==="replace")J[U]=Y;else J[U]=nJ(f,Y);else if(d(Y)&&d(f))J[U]=Tf(f,Y,A);else J[U]=Y}return J}function oJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!oJ($[A],w[A]))return!1;return!0}if(d($)&&d(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!oJ($[U],w[U]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iJ($,w,A="replace"){if(!hF($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return Tf(w,U,A)}catch{return null}}catch{return null}}function Vh($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),j=`${J}_${F.map(z).join("_")}`,G=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)S$.info(`Checking environment variable ${j} for config ${$}.${F.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))Z[B]=Y(E,F);else{let T=P1.env[j]||P1.env[G];if(T!==void 0){if(A)S$.info(`Using environment variable ${T?j:G} for config ${$}.${F.join(".")}`);if(typeof E==="number")Z[B]=Number(T);else if(typeof E==="boolean")Z[B]=T.toLowerCase()==="true";else if(Array.isArray(E))try{let h=JSON.parse(T);if(Array.isArray(h))Z[B]=h;else Z[B]=T.split(",").map((q)=>q.trim())}catch{Z[B]=T.split(",").map((h)=>h.trim())}else Z[B]=T}}}return Z}return Y(U)}async function Oh({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:U,verbose:Y=!1,checkEnv:f=!0,arrayStrategy:W="replace"}){let Z=f&&typeof U==="object"&&U!==null&&!Array.isArray(U)?Vh($,U,Y):U,B=A||P1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(Y)S$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let F=[$,`.${$}`].filter(Boolean),z=[`${$}.config`,`.${$}.config`].filter(Boolean),j=w?[w,`.${w}`]:[],G=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([B,P$(B,"config"),P$(B,".config"),J?P$(B,J):void 0].filter(Boolean)));for(let h of T){if(Y)S$.info(`Searching for configuration in: ${h}`);let N=[P$(B,"config"),P$(B,".config")].concat(J?[P$(B,J)]:[]).includes(h)?[...F,...z,...j,...G]:[...z,...F,...G,...j];for(let R of N)for(let y of E){let C=P$(h,`${R}${y}`),L=await iJ(C,Z,W);if(L!==null){if(Y)S$.success(`Configuration loaded from: ${C}`);return L}}}if($){let h=P$(b8(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)S$.info(`Checking user config directory: ${h}`);for(let N of q)for(let R of E){let y=P$(h,`${N}${R}`),C=await iJ(y,Z,W);if(C!==null){if(Y)S$.success(`Configuration loaded from user config directory: ${y}`);return C}}}if($){let h=P$(b8(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)S$.info(`Checking user config directory for dotfile configs: ${h}`);for(let N of q)for(let R of E){let y=P$(h,`${N}${R}`),C=await iJ(y,Z,W);if(C!==null){if(Y)S$.success(`Configuration loaded from user config directory dotfile: ${y}`);return C}}}if($){let h=b8(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)S$.info(`Checking user home directory for dotfile configs: ${h}`);for(let N of q)for(let R of E){let y=P$(h,`${N}${R}`),C=await iJ(y,Z,W);if(C!==null){if(Y)S$.success(`Configuration loaded from user home directory: ${y}`);return C}}}try{let h=P$(B,"package.json");if(hF(h)){let q=await import(h),N=q[$];if(!N&&w){if(N=q[w],N&&Y)S$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)S$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return Tf(Z,N,W)}catch(R){if(Y)S$.warn("Failed to merge package.json config:",R)}}}catch(h){if(Y)S$.warn("Failed to load package.json:",h)}if(Y)S$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function Xh($,w={}){let A=pJ.cwd();while(A.includes("storage"))A=xE(A,"..");let J=xE(A,$||"");if(w?.relative)return s2(pJ.cwd(),J);return J}async function _h(){try{let $=await Oh({name:"clarity",alias:"logging",defaultConfig:gJ,cwd:pJ.cwd()});return{...gJ,...$||{}}}catch{return gJ}}function j$(){if(c0.env.NODE_ENV==="test"||c0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Dh(){if(c0.env.NODE_ENV==="test"||c0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c0<"u"){let $=c0.type;if($==="renderer"||$==="worker")return!1;return!!(c0.versions&&(c0.versions.node||c0.versions.bun))}return!1}class KF{async format($){let w=await Dh(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:f1.pid,hostname:w(),environment:f1.env.NODE_ENV||"development",platform:f1.platform,version:f1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:f1.env.NODE_ENV||f1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class eJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Yf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new KF,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??X.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...lJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lJ};return{...lJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Yf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!j$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await Fh(this.config.logDirectory,lE.F_OK|lE.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await jh(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P0.from($);try{if(!kJ(this.currentLogFile))await d8(this.currentLogFile,"",{mode:420});if(U=gE(this.currentLogFile,"a",420),Eh(U,Z,{flag:"a"}),dE(U),U!==void 0)m8(U),U=void 0;if((await U1(this.currentLogFile)).size===0){if(await d8(this.currentLogFile,Z,{flag:"w",mode:420}),(await U1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<f-1){let F=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let z=W*2**Y;await new Promise((j)=>setTimeout(j,z)),Y++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{m8(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Z){if(Y===f-1){let E=Z,F=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),Z}Y++;let B=W*2**(Y-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Y1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Y1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Y1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(j$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Z])=>Z.createdAt.getTime()-W.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[W]of U.slice(f))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return n8(16).toString("hex")}generateKey(){return n8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=n8(16),J=Zh("aes-256-gcm",w,A),U=P0.isBuffer($)?$:P0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),B=P0.allocUnsafe(16+W+16);return A.copy(B,0),Y.copy(B,16),f.copy(B,16+Y.length),Z.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let J=tE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(P0.from(P0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(j$())return;if(!this.shouldWriteToFile())return;let $=await U1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await QJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await U1(A).catch(()=>null))try{if(await pE(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await xJ(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await d8(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await U1(A).catch(()=>null))await pE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await QJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await xJ(Y1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=mE($),J=Bh(w),U=tE();await Th(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),kJ(this.currentLogFile))try{let $=gE(this.currentLogFile,"r+");dE($),m8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!j$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await QJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await xJ(Y1(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Q.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||j$())return!1;let $=typeof X.env.NO_COLOR<"u",w=X.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof X.stderr<"u"&&X.stderr.isTTY||typeof X.stdout<"u"&&X.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=X.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${Q.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=Q.underline(Q.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>Q.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>Q.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>Q.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>Q.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>Q.strikethrough(J)),w}supportsHyperlinks(){if(j$())return!1;let $=X.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=X.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(zh(w)||w.startsWith("./")||w.startsWith("../"))w=Hh(w);else return null;return kJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);let{consoleText:Z,fileText:B}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":XF[$],z=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Q.gray(Z),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Q.green(Z),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.error(j),W){let G=W.split(`
|
|
137
|
-
`);for(let
|
|
131
|
+
`}function fU(){return B1.randomBytes(20)}function yj($=2048){let{privateKey:w,publicKey:A}=B1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function g9($){let w=$.export({type:"spki",format:"der"});return B1.createHash("sha1").update(w).digest()}function Mj($){let w={serialNumber:$.serialNumber||fU(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:g9($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=m9(w),Y=d9(A,$.signingKey);return{certificate:l9(Y,"CERTIFICATE"),certificateDer:Y}}function Ij($){return $.export({type:"pkcs8",format:"pem"})}function t9($){return B1.createPrivateKey($)}function p9($){let w=new B1.X509Certificate($),A=w.publicKey,Y=[],f=w.subject.split(`
|
|
132
|
+
`);for(let X of f){let[U,...W]=X.split("="),J=W.join("=");if(U&&J)Y.push({shortName:U.trim(),value:J.trim()})}return{publicKey:A,subject:Y}}async function XU($={}){I("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||G0.DEFAULT_KEY_SIZE;I("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:Y}=yj(w),f=[{shortName:"C",value:$.countryName||J$.countryName},{shortName:"ST",value:$.stateName||J$.stateName},{shortName:"L",value:$.localityName||J$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:X,notAfter:U}=YU({validityYears:$.validityYears||G0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=Mj({serialNumber:fU(),notBefore:X,notAfter:U,subject:f,publicKey:Y,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Ij(A),notBefore:X,notAfter:U}}async function UU($){if(I("ca","Generating new certificate",$.verbose),I("ca",`Options: ${aY($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=p9($.rootCA.certificate),A=t9($.rootCA.privateKey);I("ca",`Generating ${G0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let Y=G0.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:X}=yj(Y),U=$.commonName||Gj($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||J$.countryName},{shortName:"ST",value:$.stateName||J$.stateName},{shortName:"L",value:$.localityName||J$.localityName},{shortName:"O",value:$.organizationName||J$.organizationName},{shortName:"CN",value:U}],{notBefore:J,notAfter:B}=YU({validityDays:$.validityDays||G0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),E=Kj($),j=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},T=$.extKeyUsage||{serverAuth:!0},{certificate:F}=Mj({serialNumber:fU(),notBefore:J,notAfter:B,subject:W,issuer:w,publicKey:X,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:j,extendedKeyUsage:T,subjectAltName:E});return{certificate:F,privateKey:Ij(f),notBefore:J,notAfter:B}}function Cj($,w){I(C.STORAGE,`Storing certificate and private key with options: ${aY(w)}`,w?.verbose);let{certPath:A,keyPath:Y}=AU({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});I(C.STORAGE,`Certificate path: ${A}`,w?.verbose),I(C.STORAGE,`Private key path: ${Y}`,w?.verbose);let f=d8.dirname(A);if(!b0.existsSync(f))I(C.STORAGE,`Creating certificate directory: ${f}`,w?.verbose),b0.mkdirSync(f,{recursive:!0});I(C.STORAGE,"Writing certificate file",w?.verbose),b0.writeFileSync(A,$.certificate);let X=d8.dirname(Y);if(!b0.existsSync(X))I(C.STORAGE,`Creating private key directory: ${X}`,w?.verbose),b0.mkdirSync(X,{recursive:!0});return I(C.STORAGE,"Writing private key file",w?.verbose),b0.writeFileSync(Y,$.privateKey),I(C.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function Sj($,w){I(C.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=AU({basePath:w?.basePath,caCertPath:w?.caCertPath});I(C.STORAGE,`CA certificate path: ${A}`,w?.verbose);let Y=d8.dirname(A);if(!b0.existsSync(Y))I(C.STORAGE,`Creating CA certificate directory: ${Y}`,w?.verbose),b0.mkdirSync(Y,{recursive:!0});return I(C.STORAGE,"Writing CA certificate file",w?.verbose),b0.writeFileSync(A,$),I(C.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function r9($,w){if(dY.platform()!=="darwin")return!1;try{let A=GE(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return I(C.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(GE("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return I(C.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return I(C.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return I(C.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function JU($,w,A){I(C.TRUST,`Adding certificate to system trust store with options: ${aY(A)}`,A?.verbose),I(C.TRUST,"Storing certificate and private key",A?.verbose);let Y=Cj($,A);I(C.TRUST,"Storing CA certificate",A?.verbose);let f=Sj(w,A),X=dY.platform();I(C.TRUST,`Detected platform: ${X}`,A?.verbose);let U=e9[X];if(!U){let W=`Unsupported platform: ${X}`;throw I(C.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await U.addCertificate(f,A),I(C.TRUST,"Certificate successfully added to system trust store",A?.verbose),Y}var wH,lY,yE="https://acme-staging-v02.api.letsencrypt.org/directory",ME="https://acme-v02.api.letsencrypt.org/directory",LY,JH="1.2.840.10045.2.1",WH="1.2.840.10045.3.1.7",BH="1.2.840.10045.4.3.2",EH="2.5.4.3",jH="1.2.840.113549.1.9.14",TH="2.5.29.17",kY,g8,YG,fG=($)=>$,UG=($,w)=>{for(var A in w)YG($,A,{get:w[A],enumerable:!0,configurable:!0,set:XG.bind(w,A)})},JG=($,w)=>()=>($&&(w=$($=0)),w),PE,lE,J1,g1,gE,ZG,xG,$E,MY,k8,S$,g,PG,wE,iG,AE,bG,cG,N8,uG,YE,fE,y8,nG,vG,mG,dG,IY,tE,lG,L$,gG,tG,XE,CY,Z8,T$,k,pG,UE,rG,JE,aG,sG,M8,oG,WE,BE,eG,I8,$9,w9,A9,Y9,f9,SY,pE,X9,U9="0.15.6",r$,bY,m1,x8,P8,cY,i8,b8,d1,c8,u8,Yw,rE,aE,H0,c0,sE,oE,J9,B9,eE,uY,Zy,q$,i,xy,j9,Py,T9,iy,by,EE,cy,F9,z9,uy,jE,ny,vy,my,dy,ly,C8,h9,gy,R0,wj,nY,Aj,Yj,$U,fj,Xj,vY,Uj,Jj,W1,y9,Z0,ty,py,ry,zj,J$,G0,C,U1,L9,FE="[redacted]",O9,V9,K0,i$,a9,s9,o9,e9;var Lj=K$(()=>{wH=$H(import.meta.url);lY=new n1;LY=class LY extends Error{problem;httpStatus;constructor($,w,A){super($);this.name="AcmeError",this.problem=w,this.httpStatus=A}};kY=new ZE,g8=new xE,YG=Object.defineProperty;PE={};UG(PE,{withErrorRecovery:()=>cE,tryLoadConfig:()=>QG,loadConfigWithResult:()=>OG,loadConfig:()=>dE,isRetryableError:()=>yG,isConfigNotFoundError:()=>NG,isBunfigError:()=>uE,globalPerformanceMonitor:()=>g1,globalCache:()=>J1,getEnvOrDefault:()=>MG,generateConfigTypes:()=>_G,defaultGeneratedDir:()=>oE,defaultConfigDir:()=>sE,deepMergeWithArrayStrategy:()=>s8,deepMerge:()=>nE,createLibraryConfig:()=>DG,config:()=>VG,bunfigPlugin:()=>kG,applyEnvVarsToConfig:()=>c1,TypeGenerationError:()=>b8,SchemaValidationError:()=>d1,PluginError:()=>u8,PerformanceMonitor:()=>p8,FileSystemError:()=>i8,ErrorFactory:()=>Yw,EnvVarError:()=>cY,EnvProcessor:()=>tY,ConfigValidator:()=>o8,ConfigValidationError:()=>x8,ConfigNotFoundError:()=>bY,ConfigMergeError:()=>P8,ConfigLoader:()=>e8,ConfigLoadError:()=>m1,ConfigFileLoader:()=>pY,ConfigCache:()=>t8,CacheUtils:()=>gE,BunfigError:()=>r$,BrowserConfigError:()=>c8,ArrayMergeStrategies:()=>rE});J9=JG(async()=>{lE=import.meta.require,J1=new t8,g1=new p8,gE={createKey:WG,isEquivalent:BG,estimateMemoryUsage:EG},ZG=_Y(_8.cwd(),"config"),xG=_Y(_8.cwd(),"src/generated"),$E=QY.env.CLARITY_LOG_DIR||MH(FG(),"logs"),MY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$E,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},k8=await zG(),S$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},g=S$,PG=S$.red,wE=S$.green,iG=S$.yellow,AE=S$.blue,bG=S$.magenta,cG=S$.cyan,N8=S$.white,uG=S$.gray,YE=S$.bgRed,fE=S$.bgYellow,y8=S$.bold,nG=S$.dim,vG=S$.italic,mG=S$.underline,dG=S$.reset,IY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tE={debug:"\uD83D\uDD0D",info:AE("ℹ"),success:wE("✓"),warning:fE(N8(y8(" WARN "))),error:YE(N8(y8(" ERROR ")))},lG=new xY("stacks"),L$=new xY("bunfig",{showTags:!0}),gG=x$(v1.cwd(),"config"),tG=x$(v1.cwd(),"src/generated"),XE=VY.env.CLARITY_LOG_DIR||NH(KG(),"logs"),CY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:XE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Z8=await RG(),T$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},k=T$,pG=T$.red,UE=T$.green,rG=T$.yellow,JE=T$.blue,aG=T$.magenta,sG=T$.cyan,M8=T$.white,oG=T$.gray,WE=T$.bgRed,BE=T$.bgYellow,eG=T$.bgGray,I8=T$.bold,$9=T$.dim,w9=T$.italic,A9=T$.underline,Y9=T$.strikethrough,f9=T$.reset,SY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pE={debug:"\uD83D\uDD0D",info:JE("ℹ"),success:UE("✓"),warning:BE(M8(I8(" WARN "))),error:WE(M8(I8(" ERROR ")))},X9=new iY("stacks"),r$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},bY=class extends r${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A?` or alias "${A}"`:"";super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},m1=class extends r${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},x8=class extends r${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},P8=class extends r${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},cY=class extends r${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}},i8=class extends r${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},b8=class extends r${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},d1=class extends r${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},c8=class extends r${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}},u8=class extends r${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},Yw={configNotFound($,w,A){return new bY($,w,A)},configLoad($,w,A){return new m1($,w,A)},configValidation($,w,A){return new x8($,w,A)},configMerge($,w,A,Y){return new P8($,w,A,Y)},envVar($,w,A,Y){return new cY($,w,A,Y)},fileSystem($,w,A){return new i8($,w,A)},typeGeneration($,w,A){return new b8($,w,A)},schemaValidation($,w,A){return new d1($,w,A)},browserConfig($,w,A,Y){return new c8($,w,A,Y)},plugin($,w,A){return new u8($,w,A)}},rE={replace:"replace",concat:"concat",smart:"smart"},aE=/^https?:\/\//,H0=new iY("bunfig",{showTags:!0}),c0=new e8,sE=P$(Kw.cwd(),"config"),oE=P$(Kw.cwd(),"src/generated")});B9=DY.env.CLARITY_LOG_DIR||lH(W9(),"logs"),eE={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:B9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uY={...eE},Zy=(async()=>{try{let{loadConfig:$}=await J9().then(()=>PE),w=await $({name:"clarity",alias:"logging",defaultConfig:eE,cwd:DY.cwd()});if(w)Object.assign(uY,w)}catch{}return uY})();q$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=q$,xy=q$.red,j9=q$.green,Py=q$.yellow,T9=q$.blue,iy=q$.magenta,by=q$.cyan,EE=q$.white,cy=q$.gray,F9=q$.bgRed,z9=q$.bgYellow,uy=q$.bgGray,jE=q$.bold,ny=q$.dim,vy=q$.italic,my=q$.underline,dy=q$.strikethrough,ly=q$.reset,C8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},h9={debug:"\uD83D\uDD0D",info:T9("ℹ"),success:j9("✓"),warning:z9(EE(jE(" WARN "))),error:F9(EE(jE(" ERROR ")))};gy=new rY("stacks");R0=class R0 extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};wj=class wj extends R0{code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};nY=class nY extends R0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};Aj=class Aj extends R0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Yj=class Yj extends R0{code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};$U=class $U extends R0{code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};fj=class fj extends R0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};Xj=class Xj extends R0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};vY=class vY extends R0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Uj=class Uj extends R0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};Jj=class Jj extends R0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};W1={configNotFound($,w,A){return new wj($,w,A)},configLoad($,w,A){return new nY($,w,A)},configValidation($,w,A){return new Aj($,w,A)},configMerge($,w,A,Y){return new Yj($,w,A,Y)},envVar($,w,A,Y){return new $U($,w,A,Y)},fileSystem($,w,A){return new fj($,w,A)},typeGeneration($,w,A){return new Xj($,w,A)},schemaValidation($,w,A){return new vY($,w,A)},browserConfig($,w,A,Y){return new Uj($,w,A,Y)},plugin($,w,A){return new Jj($,w,A)}};y9=/^https?:\/\//;Z0=new rY("bunfig",{showTags:!0});ty=new Fj;py=Y0(gY.cwd(),"config"),ry=Y0(gY.cwd(),"src/generated"),zj={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:U8.join(X8.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:U8.join(X8.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:U8.join(X8.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},J$=zj,G0={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"},C={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},U1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};L9=S9(I9);O9=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),V9=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;K0={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},i$={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"};a9={platform:"darwin",async addCertificate($,w){if(await r9($,w?.verbose)){I(C.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),U1.success("Certificate is already trusted in system keychain");return}I(C.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Aw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let Y=A||J$.commonName;I(C.TRUST,`Removing certificate ${Y} from macOS keychain`,w?.verbose);try{await Aw(`sudo security delete-certificate -c "${Y}" /Library/Keychains/System.keychain`),I(C.TRUST,`Removed certificate ${Y} from macOS keychain`,w?.verbose)}catch(f){throw I(C.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},s9={platform:"win32",async addCertificate($,w){I(C.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Aw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let Y=A||J$.commonName;I(C.TRUST,`Removing certificate ${Y} from Windows certificate store`,w?.verbose);try{await Aw(`certutil -delstore -enterprise Root "${Y}"`),I(C.TRUST,`Removed certificate ${Y} from Windows certificate store`,w?.verbose)}catch(f){throw I(C.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},o9={platform:"linux",async addCertificate($,w){I(C.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=dY.homedir(),Y=G0.LINUX_CERT_DB_FILENAME,f=G0.LINUX_TRUST_ARGS;I(C.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let X=v8(A,Y);if(X.length===0){U1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of X){I(C.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{I(C.TRUST,`Attempting to delete existing cert for ${J$.commonName}`,w?.verbose),await Aw(`certutil -d sql:${U} -D -n ${J$.commonName}`)}catch(W){I(C.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}I(C.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Aw(`certutil -d sql:${U} -A -t ${f} -n ${J$.commonName} -i ${$}`),U1.info(`Cert added to ${U}`)}},async removeCertificate($,w,A){let Y=A||J$.commonName;I(C.TRUST,`Removing certificate ${Y} from Linux certificate store`,w?.verbose);let f=dY.homedir(),X=G0.LINUX_CERT_DB_FILENAME;I(C.TRUST,`Searching for certificate databases in ${f}`,w?.verbose);let U=v8(f,X);if(U.length===0){U1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){I(C.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Aw(`certutil -d sql:${W} -D -n "${Y}"`),U1.info(`Cert removed from ${W}`)}catch(J){I(C.TRUST,`Error removing cert from ${W}: ${J}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${J}`)}}}},e9={darwin:a9,win32:s9,linux:o9}});var WU=K$(()=>{Lj()});import{homedir as BU}from"node:os";import{join as EU,resolve as lM}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",$5,jU;var TU=K$(()=>{w8();$5={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:EU(BU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:EU(BU(),".stacks","ssl","stacks.localhost.crt"),keyPath:EU(BU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},jU=$5});import{execSync as w5}from"node:child_process";function Oj($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function sY($){try{let w=w5(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return Oj(w)}catch{return null}}var FU=()=>{};import{existsSync as Vj,statSync as Qj}from"fs";import{existsSync as DU,mkdirSync as J5,readdirSync as W5,writeFileSync as B5}from"fs";import{homedir as E1}from"os";import{dirname as _j,resolve as c$}from"path";import Rw from"process";import{join as E5,relative as j5,resolve as Dj}from"path";import zf from"process";import{existsSync as zT,mkdirSync as fI,readdirSync as XI,writeFileSync as UI}from"fs";import{homedir as zU}from"os";import{dirname as BI,resolve as b$}from"path";import p1 from"process";import{join as T5,relative as F5,resolve as kj}from"path";import hf from"process";import{existsSync as hT,mkdirSync as zI,readdirSync as hI,writeFileSync as HI}from"fs";import{dirname as KI,resolve as Hf}from"path";import kU from"process";import{Buffer as Xw}from"buffer";import{createCipheriv as z5,createDecipheriv as h5,randomBytes as hU}from"crypto";import{closeSync as HU,createReadStream as Zj,createWriteStream as H5,existsSync as GU,fsyncSync as xj,openSync as Pj,writeFileSync as G5}from"fs";import{access as K5,constants as ij,mkdir as R5,readdir as oY,rename as bj,stat as j1,unlink as eY,writeFile as KU}from"fs/promises";import{join as T1}from"path";import O$ from"process";import{pipeline as q5}from"stream/promises";import{createGzip as cj}from"zlib";import F1 from"process";import v0 from"process";import{Buffer as u0}from"buffer";import{createCipheriv as N5,createDecipheriv as y5,randomBytes as RU}from"crypto";import{closeSync as qU,createReadStream as uj,createWriteStream as M5,existsSync as $f,fsyncSync as nj,openSync as vj,writeFileSync as I5}from"fs";import{access as C5,constants as mj,mkdir as S5,readdir as wf,rename as dj,stat as z1,unlink as Af,writeFile as NU}from"fs/promises";import{isAbsolute as L5,join as h1,resolve as O5}from"path";import Q from"process";import{pipeline as V5}from"stream/promises";import{createGzip as lj}from"zlib";import H1 from"process";import m0 from"process";import Yf from"process";import{existsSync as ff}from"fs";import{resolve as yU}from"path";import{existsSync as Q5}from"fs";import{existsSync as _5,readdirSync as D5}from"fs";import{extname as MU,resolve as gj}from"path";import k5 from"process";import{join as ZK,relative as xK,resolve as fT}from"path";import Mf from"process";import{Buffer as n0}from"buffer";import{createCipheriv as bK,createDecipheriv as cK,randomBytes as OU}from"crypto";import{closeSync as VU,createReadStream as XT,createWriteStream as uK,existsSync as Uf,fsyncSync as UT,openSync as JT,writeFileSync as nK}from"fs";import{access as vK,constants as WT,mkdir as mK,readdir as Jf,rename as BT,stat as G1,unlink as Wf,writeFile as QU}from"fs/promises";import{isAbsolute as dK,join as K1,resolve as lK}from"path";import _ from"process";import{pipeline as gK}from"stream/promises";import{createGzip as ET}from"zlib";import R1 from"process";import d0 from"process";function f5($,w){this[$]=Y5.bind(null,w)}class mU{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!Vj($))return!0;return Qj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=Vj(A)?Qj(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class dU{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function Z5($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function x5($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function P5($){return $.getStats().size*2}function lU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&o(w[0])&&"id"in w[0]&&w[0].id===3&&o(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(o(w)&&o($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(o($)&&"arr"in $&&Array.isArray($.arr)&&o(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&o(w[0])&&o($[0])){let Y=[...w];for(let f of $)if(o(f)&&"name"in f){if(!Y.find((U)=>o(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(o(f)&&"path"in f){if(!Y.find((U)=>o(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>Gf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!o(w)||!o($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(o(f)&&o(A[Y]))A[Y]=lU(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&o(f[0])&&o(A[Y][0])){let X=[...f];for(let U of A[Y])if(o(U)&&"name"in U){if(!X.find((J)=>o(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(o(U)&&"path"in U){if(!X.find((J)=>o(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>Gf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function Gf($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!Gf($[A],w[A]))return!1;return!0}if(o($)&&o(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!Gf($[f],w[f]))return!1}return!0}return!1}function o($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function i5($,w){if(!hT($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return lU(w,Y)}catch{return null}}catch{return null}}async function b5({name:$="",cwd:w,defaultConfig:A}){let Y=w||kU.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=Hf(Y,`${U}${W}`),B=await i5(J,A);if(B!==null)return B}try{let U=Hf(Y,"package.json");if(hT(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return lU(A,J)}catch{}}}catch{}return A}function c5($,w={}){let A=hf.cwd();while(A.includes("storage"))A=kj(A,"..");let Y=kj(A,$||"");if(w?.relative)return F5(hf.cwd(),Y);return Y}async function u5(){try{let $=await b5({name:"clarity",defaultConfig:Ef,cwd:hf.cwd(),endpoint:"",headers:{}});return{...Ef,...$}}catch{return Ef}}function f$(){if(v0.env.NODE_ENV==="test"||v0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function n5(){if(v0.env.NODE_ENV==="test"||v0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v0<"u"){let $=v0.type;if($==="renderer"||$==="worker")return!1;return!!(v0.versions&&(v0.versions.node||v0.versions.bun))}return!1}class HT{async format($){let w=await n5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:F1.pid,hostname:w(),environment:F1.env.NODE_ENV||"development",platform:F1.platform,version:F1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:F1.env.NODE_ENV||F1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Kf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...xU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new HT,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...jf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...jf};return{...jf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:xU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await K5(this.config.logDirectory,ij.F_OK|ij.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await R5(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Xw.from($);try{if(!GU(this.currentLogFile))await KU(this.currentLogFile,"",{mode:420});if(f=Pj(this.currentLogFile,"a",420),G5(f,J,{flag:"a"}),xj(f),f!==void 0)HU(f),f=void 0;if((await j1(this.currentLogFile)).size===0){if(await KU(this.currentLogFile,J,{flag:"w",mode:420}),(await j1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{HU(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return T1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return T1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f$())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return hU(16).toString("hex")}generateKey(){return hU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=hU(16),Y=z5("aes-256-gcm",w,A),f=Xw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Xw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=cj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Xw.from(Xw.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f$())return;let $=await j1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await oY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await j1(A).catch(()=>null))try{if(await bj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await eY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await KU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await j1(A).catch(()=>null))await bj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await oY(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await eY(T1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=Zj($),Y=H5(w),f=cj();await q5(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),GU(this.currentLogFile))try{let $=Pj(this.currentLogFile,"r+");xj($),HU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await oY(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await eY(T1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=O$.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${t.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!f$()){let B=ST[$],E=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
133
|
+
`);for(let F of T)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:t.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!f$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let J=`${X} ${this.environment}.${$.toUpperCase()}: ${U}
|
|
134
|
+
`;if(W)J+=`${W}
|
|
135
|
+
`;J=J.replace(this.ANSI_PATTERN,""),await this.writeToFile(J)}time($){let w=performance.now();if(this.fancy&&!f$()){let A=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:t.blue("◐"),tag:A,message:`${t.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
136
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!f$()){let E=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:t.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!f$())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new Kf(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(f$())throw Error("createReadStream is not supported in browser environments");if(!GU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=Xw.isBuffer($)?$:Xw.from($,"base64"),f=Y.slice(0,16),X=Y.slice(-16),U=Y.slice(16,-16),W=h5("aes-256-gcm",A,f);return W.setAuthTag(X),Xw.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return f$()}isServerMode(){return!f$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w);if(this.fancy&&!f$()){let X=$.split(`
|
|
137
|
+
`),U=Math.max(...X.map((E)=>E.length))+2,W=`┌${"─".repeat(U)}┐`,J=`└${"─".repeat(U)}┘`,B=X.map((E)=>{let j=" ".repeat(U-E.length-2);return`│ ${E}${j} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:t.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(W)})),B.forEach((E)=>console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(E),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(J),showTimestamp:!1}))}else if(!f$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let f=`${Y} ${this.environment}.INFO: [BOX] ${$}
|
|
138
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt($){if(f$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${t.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();O$.stdin.removeListener("data",A);try{if(typeof O$.stdin.setRawMode==="function")O$.stdin.setRawMode(!1)}catch{}O$.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof O$.stdin.setRawMode==="function")O$.stdin.setRawMode(!0)}catch{}O$.stdin.resume(),O$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(J,B)=>{if(B==="%")return"%";if(W>=w.length)return J;let E=w[W++];switch(B){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return J}}),W<w.length)A+=` ${w.slice(W).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!f$()){let U=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",W=t.blue("◐");console.error(`${W} ${U} ${t.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
139
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||f$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),W!==void 0)this.activeProgressBar.message=W;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||f$())return;O$.stdout.write(`${"\r".padEnd(O$.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||f$()||!O$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=t.green("━".repeat(Y)),U=t.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=w||A===100?t.green("✓"):t.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${t.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=O$.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,O$.stdout.write($.lastRenderedLine),w)O$.stdout.write(`
|
|
140
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f$()||!O$.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await oY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=T1(this.config.logDirectory,Y);if($.before)try{if((await j1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await eY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function Bf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let Y=[...w];for(let f of $)if(d(f)&&"name"in f){if(!Y.find((U)=>d(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(d(f)&&"path"in f){if(!Y.find((U)=>d(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>Rf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!d(w)||!d($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(d(f)&&d(A[Y]))A[Y]=Bf(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&d(f[0])&&d(A[Y][0])){let X=[...f];for(let U of A[Y])if(d(U)&&"name"in U){if(!X.find((J)=>d(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(d(U)&&"path"in U){if(!X.find((J)=>d(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>Rf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function gU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:Bf($,w);if(Array.isArray($))return A==="replace"?w:Bf($,w);if(!d(w)||!d($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=Bf(U,X);else if(d(X)&&d(U))Y[f]=gU(U,X,A);else Y[f]=X}return Y}function Rf($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!Rf($[A],w[A]))return!1;return!0}if(d($)&&d(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!Rf($[f],w[f]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Xf($,w,A="replace"){if(!zT($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return gU(w,f,A)}catch{return null}}catch{return null}}function v5($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((h)=>h.toUpperCase()).join("_")}`;if(A)Q$.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let h=p1.env[F]||p1.env[H];if(h!==void 0){if(A)Q$.info(`Using environment variable ${h?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(h);else if(typeof E==="boolean")J[B]=h.toLowerCase()==="true";else if(Array.isArray(E))try{let G=JSON.parse(h);if(Array.isArray(G))J[B]=G;else J[B]=h.split(",").map((K)=>K.trim())}catch{J[B]=h.split(",").map((G)=>G.trim())}else J[B]=h}}}return J}return X(f)}async function m5({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?v5($,f,X):f,B=A||p1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)Q$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],h=Array.from(new Set([B,b$(B,"config"),b$(B,".config"),Y?b$(B,Y):void 0].filter(Boolean)));for(let G of h){if(X)Q$.info(`Searching for configuration in: ${G}`);let R=[b$(B,"config"),b$(B,".config")].concat(Y?[b$(B,Y)]:[]).includes(G)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let M of R)for(let N of E){let y=b$(G,`${M}${N}`),S=await Xf(y,J,W);if(S!==null){if(X)Q$.success(`Configuration loaded from: ${y}`);return S}}}if($){let G=b$(zU(),".config",$),K=["config",`${$}.config`];if(w)K.push(`${w}.config`);if(X)Q$.info(`Checking user config directory: ${G}`);for(let R of K)for(let M of E){let N=b$(G,`${R}${M}`),y=await Xf(N,J,W);if(y!==null){if(X)Q$.success(`Configuration loaded from user config directory: ${N}`);return y}}}if($){let G=b$(zU(),".config"),K=[`.${$}.config`];if(w)K.push(`.${w}.config`);if(X)Q$.info(`Checking user config directory for dotfile configs: ${G}`);for(let R of K)for(let M of E){let N=b$(G,`${R}${M}`),y=await Xf(N,J,W);if(y!==null){if(X)Q$.success(`Configuration loaded from user config directory dotfile: ${N}`);return y}}}if($){let G=zU(),K=[`.${$}.config`,`.${$}`];if(w)K.push(`.${w}.config`),K.push(`.${w}`);if(X)Q$.info(`Checking user home directory for dotfile configs: ${G}`);for(let R of K)for(let M of E){let N=b$(G,`${R}${M}`),y=await Xf(N,J,W);if(y!==null){if(X)Q$.success(`Configuration loaded from user home directory: ${N}`);return y}}}try{let G=b$(B,"package.json");if(zT(G)){let K=await import(G),R=K[$];if(!R&&w){if(R=K[w],R&&X)Q$.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(X)Q$.success(`Configuration loaded from package.json: ${R===K[$]?$:w}`);return gU(J,R,W)}catch(M){if(X)Q$.warn("Failed to merge package.json config:",M)}}}catch(G){if(X)Q$.warn("Failed to load package.json:",G)}if(X)Q$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function d5($,w={}){let A=zf.cwd();while(A.includes("storage"))A=Dj(A,"..");let Y=Dj(A,$||"");if(w?.relative)return j5(zf.cwd(),Y);return Y}async function l5(){try{let $=await m5({name:"clarity",alias:"logging",defaultConfig:Tf,cwd:zf.cwd()});return{...Tf,...$||{}}}catch{return Tf}}function z$(){if(m0.env.NODE_ENV==="test"||m0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function g5(){if(m0.env.NODE_ENV==="test"||m0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof m0<"u"){let $=m0.type;if($==="renderer"||$==="worker")return!1;return!!(m0.versions&&(m0.versions.node||m0.versions.bun))}return!1}class GT{async format($){let w=await g5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:H1.pid,hostname:w(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new GT,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Ff,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Ff};return{...Ff,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!z$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await C5(this.config.logDirectory,mj.F_OK|mj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await S5(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:u0.from($);try{if(!$f(this.currentLogFile))await NU(this.currentLogFile,"",{mode:420});if(f=vj(this.currentLogFile,"a",420),I5(f,J,{flag:"a"}),nj(f),f!==void 0)qU(f),f=void 0;if((await z1(this.currentLogFile)).size===0){if(await NU(this.currentLogFile,J,{flag:"w",mode:420}),(await z1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{qU(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return h1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return h1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return h1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(z$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return RU(16).toString("hex")}generateKey(){return RU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=RU(16),Y=N5("aes-256-gcm",w,A),f=u0.isBuffer($)?$:u0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=u0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=lj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(u0.from(u0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(z$())return;if(!this.shouldWriteToFile())return;let $=await z1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wf(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await z1(A).catch(()=>null))try{if(await dj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Af(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await NU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await z1(A).catch(()=>null))await dj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await wf(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Af(h1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=uj($),Y=M5(w),f=lj();await V5(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),$f(this.currentLogFile))try{let $=vj(this.currentLogFile,"r+");nj($),qU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!z$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await wf(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Af(h1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Z.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||z$())return!1;let $=typeof Q.env.NO_COLOR<"u",w=Q.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Q.stderr<"u"&&Q.stderr.isTTY||typeof Q.stdout<"u"&&Q.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=Q.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${Z.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=Z.underline(Z.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>Z.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>Z.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>Z.strikethrough(Y)),w}supportsHyperlinks(){if(z$())return!1;let $=Q.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=Q.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(L5(w)||w.startsWith("./")||w.startsWith("../"))w=O5(w);else return null;return $f(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":LT[$],T=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
141
|
+
`);for(let h of H)if(h.trim()&&!h.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:Z.gray(` ${h}`),level:$,showTimestamp:!1}))}break}}else if(!z$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
138
142
|
`;if(W)E+=`${W}
|
|
139
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,
|
|
140
|
-
`);if(this[
|
|
141
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
142
|
-
`),
|
|
143
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
144
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
145
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
146
|
-
|
|
147
|
-
`;for(let
|
|
148
|
-
`,A+=` Type: ${
|
|
149
|
-
`,A+=` Description: ${
|
|
150
|
-
`,A+=` Example: ${
|
|
143
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!z$()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!z$()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!z$()&&Q.stdout.isTTY)Q.stdout.write(`
|
|
144
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!z$()&&Q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":Z.blue("◐"),tag:A,message:`${Z.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
145
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":Z.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!z$())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new qf(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(z$())throw Error("createReadStream is not supported in browser environments");if(!$f(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=u0.isBuffer($)?$:u0.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=y5("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=u0.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return z$()}isServerMode(){return!z$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
146
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:Z.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:Z.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:Z.cyan(E),showTimestamp:!1}))}else if(!z$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
147
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(z$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${Z.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();Q.stdin.removeListener("data",A);try{if(typeof Q.stdin.setRawMode==="function")Q.stdin.setRawMode(!1)}catch{}Q.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof Q.stdin.setRawMode==="function")Q.stdin.setRawMode(!0)}catch{}Q.stdin.resume(),Q.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${Z.blue("◐")} `;console.error(`${B}${J} ${Z.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
148
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!Q.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=Z.green("━".repeat(Y)),U=Z.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?Z.green("✓"):Z.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${Z.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=Q.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,Q.stdout.write($.lastRenderedLine),w)Q.stdout.write(`
|
|
149
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||z$()||!Q.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await wf(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=h1(this.config.logDirectory,Y);if($.before)try{if((await z1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await Af(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function KT($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:f=()=>!0,fallback:X}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(J){if(U=J instanceof Error?J:Error(String(J)),W===A||!f(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(X!==void 0)return X;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function RT($){return $ instanceof o$}function t5($){return $ instanceof Nf}function p5($){if(RT($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class Cf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:f=!0,useBackwardCompatibility:X=!0,customParsers:U={},verbose:W=!1,trackPerformance:J=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let E=Y||this.generateEnvPrefix($),j={...w};return this.processObject(j,[],E,{useCamelCase:f,useBackwardCompatibility:X,customParsers:U,verbose:W,configName:$}),{config:j,source:{type:"environment",priority:50,timestamp:new Date}}};if(J)return s1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=U.map((E)=>this.formatEnvKey(E,Y.useCamelCase)),J=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((E)=>E.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,U,A,Y);else{let E=Yf.env[J]||(B?Yf.env[B]:void 0);if(E!==void 0){if(Y.verbose){let j=Yf.env[J]?J:B}try{$[f]=this.parseEnvironmentValue(E,typeof X,J,Y.customParsers,Y.configName)}catch(j){if(j instanceof yf)throw j;throw Uw.envVar(J,E,typeof X,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,f){for(let[X,U]of Object.entries(Y))try{return U($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Uw.envVar(A,$,`${w} (via ${X.name} parser)`,f)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,f]of Object.entries(Yf.env))if(Y.startsWith(A)&&f!==void 0)w[Y]=f;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(f){Y.push(`Cannot parse value "${w}" as ${A}: ${f}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:f="text"}=A,X=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],X,U),f){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[f,X]of Object.entries($)){let U=[...w,f],W=`${A}_${U.map((J)=>this.formatEnvKey(J,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,U,A,Y);else Y.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${U.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
150
|
+
|
|
151
|
+
`;for(let Y of $)A+=`${Y.key}
|
|
152
|
+
`,A+=` Type: ${Y.type}
|
|
153
|
+
`,A+=` Description: ${Y.description}
|
|
154
|
+
`,A+=` Example: ${Y.example}
|
|
151
155
|
|
|
152
156
|
`;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
|
|
153
157
|
|
|
154
158
|
`;A+=`| Variable | Type | Description | Example |
|
|
155
159
|
`,A+=`|----------|------|-------------|----------|
|
|
156
|
-
`;for(let
|
|
157
|
-
`;return A}}function xh($,w){let A=SF("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function IF($,w,A={}){return yF($,w,A,new WeakMap)}function yF($,w,A,J){let{arrayMergeMode:U="replace",skipNullish:Y=!1,customMerger:f}=A;if(w===null||w===void 0)return Y?$:w;if(f){let W=f($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return CF($,w,U,J);if(!A0(w)||!A0($))return w;return ch($,w,A,J)}function CF($,w,A,J){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return Ph($,w);case"smart":return bh($,w,J);default:return w}return w}function Ph($,w){let A=[...w];for(let J of $)if(!A.some((U)=>Jf(U,J)))A.push(J);return A}function bh($,w,A){if(w.length===0)return $;if($.length===0)return w;if(A0(w[0])&&A0($[0]))return ih($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let U of $)if(!J.includes(U))J.push(U);return J}return w}function ih($,w,A){let J=[...w];for(let U of $){if(!A0(U)){J.push(U);continue}let Y=["id","name","key","path","type"],f=!1;for(let W of Y)if(W in U){if(J.find((B)=>A0(B)&&(W in B)&&B[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function ch($,w,A,J){let U=w;if(A0(U)&&J.has(U))return J.get(U);let Y={...$};if(A0(U))J.set(U,Y);for(let f in U){if(!Object.prototype.hasOwnProperty.call(U,f))continue;let W=U[f],Z=Y[f];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){Y[f]=W;continue}if(A0(W)&&A0(Z))Y[f]=yF(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=CF(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function Gf($,w,A="replace"){return IF($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function Jf($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!Jf($[A],w[A]))return!1;return!0}if(A0($)&&A0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!Jf($[U],w[U]))return!1}return!0}return!1}function A0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class YU{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:U=!0,cacheTtl:Y,trackPerformance:f=!0,verbose:W=!1}=A;if(U){let B=E1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let Z=async()=>{if(!bJ($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),F=E.default||E,z="default"in E,j=Object.keys(E).length>0;if(!z&&!j)throw new b1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new b1($,Error("Configuration must export a valid object"),"unknown");let h={config:Gf(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)E1.setWithFileCheck("file",h,$,Y);return h}catch(B){throw B instanceof Error?$w.configLoad($,B):$w.configLoad($,Error(String(B)))}};if(f)return c1.track("loadFromPath",Z,{path:$});return Z()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let U=await this.loadFromPath(J,w,A);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(A.verbose)console.warn(`Failed to load config from ${J}:`,U)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),U=[];for(let Y of J)for(let f of this.extensions)U.push(g8(w,`${Y}${f}`));return U}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return RF(async()=>{return bJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!bJ($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=g8($,`${Y}${f}`);if(await this.checkFileAccess(W))J.push(W)}}else try{let{readdirSync:U}=await import("fs"),Y=U($);for(let f of Y)if(this.looksLikeConfigFile(f)){let W=g8($,f);if(await this.checkFileAccess(W))J.push(W)}}catch{return[]}return J}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!bJ($))return w.push("Configuration file does not exist"),w;let A=await import($),J=A.default||A;if(J===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof J!=="object"||J===null)w.push("Configuration must be an object");else if(Array.isArray(J))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),Y=U($,"utf8");JSON.parse(Y)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(J)=>{try{let U=await this.loadFromPath(J,{},w);if(U)A.set(J,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${J}:`,U)}})),A}}class hf{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,B=async()=>{let E=[],F=[],z={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,z);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],z);else return this.validateWithJSONSchema($,w,z)}catch(j){return E.push({path:"",message:`Validation failed: ${j}`,rule:"system"}),{isValid:!1,errors:E,warnings:F}}};if(W)return await c1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!Gh(w))throw new i1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),U=J.default||J;if(Array.isArray(U))return this.validateWithRules($,U,A);else return this.validateWithJSONSchema($,U,A)}catch(J){throw new i1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],U=[];return this.validateObjectAgainstSchema($,w,"",J,U,A),{isValid:J.length===0,errors:J,warnings:U}}validateObjectAgainstSchema($,w,A,J,U,Y){if(Y.validateTypes&&w.type){let f=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(f)){if(J.push({path:A,message:`Expected type ${W.join(" or ")}, got ${f}`,expected:W.join(" or "),actual:f,rule:"type"}),Y.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(J.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),Y.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)J.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)J.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))J.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)J.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)J.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let f=0;f<$.length;f++){let W=A?`${A}[${f}]`:`[${f}]`;if(this.validateObjectAgainstSchema($[f],w.items,W,J,U,Y),Y.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let f=$;if(Y.validateRequired&&w.required){for(let W of w.required)if(!(W in f)){if(J.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),Y.stopOnFirstError)return}}if(w.properties){for(let[W,Z]of Object.entries(w.properties))if(W in f){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,B,J,U,Y),Y.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let Z of Object.keys(f))if(!W.has(Z))U.push({path:A?`${A}.${Z}`:Z,message:`Additional property '${Z}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],U=[];for(let Y of w)try{let f=this.getValueByPath($,Y.path),W=this.validateWithRule(f,Y,Y.path);if(J.push(...W),A.stopOnFirstError&&J.length>0)break}catch(f){J.push({path:Y.path,message:`Rule validation failed: ${f}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:U}}validateWithRule($,w,A){let J=[];if(w.required&&($===void 0||$===null))return J.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),J;if($===void 0||$===null)return J;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))J.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))J.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)J.push({path:A,message:w.message||U,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let U of A)if(J&&typeof J==="object"&&U in J)J=J[U];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,U,Y,f]=J;w.push({path:U,required:!Y,type:this.mapTypeScriptType(f)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:DF},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class qf{fileLoader=new YU;envProcessor=new UU;validator=new hf;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:U,validate:Y,...f}=$;try{if(A?.enabled){let Z=this.checkCache(f.name||"",f);if(Z)return Z}let W;try{W=await this.loadConfigurationStrategies(f,!0,A)}catch(Z){let B=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(B)throw Z;W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`No configuration file found for "${f.name||"config"}", using defaults with environment variables`]}}else if(Z instanceof Error&&Z.name==="ConfigLoadError"){let E=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),F=!E&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),z=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(B&&(z||E))throw Z;if(F&&(!B||!z))W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Z.message}`]};else throw Z}else W={...await this.applyEnvironmentVariables(f.name||"",f.defaultConfig,f.checkEnv!==!1,f.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Z instanceof Error?Z.message:String(Z)}`]}}if(U||Y)await this.validateConfiguration(W.config,U,Y,f.name);if(A?.enabled&&W)this.cacheResult(f.name||"",W,A,f);if(J?.enabled){let Z={operation:"loadConfig",duration:Date.now()-w,configName:f.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(Z);if(J.slowThreshold&&Z.duration>J.slowThreshold)H0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw H0.error(`Configuration loading failed after ${Z}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:U,cwd:Y,configDir:f,defaultConfig:W,checkEnv:Z=!0,arrayStrategy:B="replace",verbose:E=!1}=$,F=Y||jw.cwd(),z=[],j=await this.loadLocalConfiguration(J,U,F,f,W,B,E,Z,A);if(j)return z.push(...this.getLocalSearchPaths(J,U,F,f)),this.finalizeResult(j,z,Z,J,E);let G=await this.loadHomeConfiguration(J,U,W,B,E,Z);if(G)return z.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(G,z,Z,J,E);let T=await this.loadPackageJsonConfiguration(J,U,F,W,B,E,Z);if(T)return z.push(b$(F,"package.json")),this.finalizeResult(T,z,Z,J,E);if(z.push(...this.getAllSearchPaths(J,U,F,f)),w)throw $w.configNotFound(J,z,U);return{...await this.applyEnvironmentVariables(J,W,Z,E),warnings:[`No configuration file found for "${J}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let B=W?x1($,U,f):U,E=this.getLocalDirectories(A,J);for(let F of E){if(f)H0.info(`Searching for configuration in: ${F}`);let z=this.fileLoader.generateConfigPaths($,F,w),j=await this.fileLoader.tryLoadFromPaths(z,B,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(j){if(f)H0.success(`Configuration loaded from: ${j.source.path}`);return j}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?x1($,A,U):A,W=[b$($1(),".config",$),b$($1(),".config"),$1()];for(let Z of W){if(U)H0.info(`Checking home directory: ${Z}`);let B=this.fileLoader.generateConfigPaths($,Z,w),E=await this.fileLoader.tryLoadFromPaths(B,f,{arrayStrategy:J,verbose:U});if(E){if(U)H0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?x1($,J,Y):J;try{let Z=b$(A,"package.json");if(!wf(Z))return null;let B=await import(Z),E=B[$],F=$;if(!E&&w)E=B[w],F=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(Y)H0.success(`Configuration loaded from package.json: ${F}`);return{config:Gf(W,E,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)H0.warn("Failed to load package.json:",[Z instanceof Error?Z:Error(String(Z))])}return null}async applyEnvironmentVariables($,w,A,J){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:x1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let U=[];if(A){let Y=A($);if(Y)U.push(...Y)}if(w){let Y=await this.validator.validateConfiguration($,w);if(!Y.isValid)U.push(...Y.errors.map((f)=>f.path?`${f.path}: ${f.message}`:f.message))}if(U.length>0)throw $w.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return E1.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);E1.set(U,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,b$($,"config"),b$($,".config"),w?b$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let U=[];return U.push(...this.getLocalSearchPaths($,w,A,J)),U.push(...this.getHomeSearchPaths($,w)),U.push(b$(A,"package.json")),U}getLocalSearchPaths($,w,A,J){let U=this.getLocalDirectories(A,J),Y=[];for(let f of U)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}getHomeSearchPaths($,w){if(!$)return[];let A=[b$($1(),".config",$),b$($1(),".config"),$1()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function aE($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),J=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||J}async function uh($){return v0.loadConfig({...$,__strictErrorHandling:!0})}async function LF($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await v0.loadConfig($);else J=await v0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let U=J instanceof Error?J.name:"UnknownError",Y=J instanceof Error?J.message:String(J);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||Y.includes("config"))&&$.verbose)H0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await v0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function vh($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await v0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&aE(A)))return(await v0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await v0.loadConfig({...$,cwd:$.cwd||jw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&aE(w)))return(await v0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function nh($,w,A="replace"){let J=new YU;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function x1($,w,A=!1){let J=new UU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[B,E]of Object.entries(f)){let F=[...W,B],z=[`${U}_${F.join("_").toUpperCase()}`,`${U}_${F.map((T)=>T.toUpperCase()).join("")}`,`${U}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],j,G;for(let T of z)if(j=jw.env[T],j!==void 0){G=T;break}if(j!==void 0&&G)if(typeof E==="boolean")Z[B]=["true","1","yes"].includes(j.toLowerCase());else if(typeof E==="number"){let T=Number(j);if(!Number.isNaN(T))Z[B]=T}else if(Array.isArray(E))try{Z[B]=JSON.parse(j)}catch{Z[B]=j.split(",").map((T)=>T.trim())}else Z[B]=j;else if(E&&typeof E==="object"&&!Array.isArray(E))Z[B]=Y(E,F)}return Z}return Y(w)}function mh($){let w=b$(jw.cwd(),$.configDir),A=b$(jw.cwd(),$.generatedDir),J=b$(A,"config-types.ts");if(!wf(QE(J)))p2(QE(J),{recursive:!0,mode:511});let U=wf(w)?t2(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${q7}
|
|
158
|
-
export type ConfigNames = ${
|
|
159
|
-
`;
|
|
160
|
-
${
|
|
160
|
+
`;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
|
|
161
|
+
`;return A}}function r5($,w){let A=IT("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function qT($,w,A={}){return NT($,w,A,new WeakMap)}function NT($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return yT($,w,f,Y);if(!U0(w)||!U0($))return w;return e5($,w,A,Y)}function yT($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return a5($,w);case"smart":return s5($,w,Y);default:return w}return w}function a5($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>ZU(f,Y)))A.push(Y);return A}function s5($,w,A){if(w.length===0)return $;if($.length===0)return w;if(U0(w[0])&&U0($[0]))return o5($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function o5($,w,A){let Y=[...w];for(let f of $){if(!U0(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>U0(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function e5($,w,A,Y){let f=w;if(U0(f)&&Y.has(f))return Y.get(f);let X={...$};if(U0(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(U0(W)&&U0(J))X[U]=NT(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=yT(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function tU($,w,A="replace"){return qT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function ZU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!ZU($[A],w[A]))return!1;return!0}if(U0($)&&U0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!ZU($[f],w[f]))return!1}return!0}return!1}function U0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Sf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=q1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!ff($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new r1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new r1($,Error("Configuration must export a valid object"),"unknown");let G={config:tU(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)q1.setWithFileCheck("file",G,$,X);return G}catch(B){throw B instanceof Error?Uw.configLoad($,B):Uw.configLoad($,Error(String(B)))}};if(U)return s1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(yU(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return KT(async()=>{return ff($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!ff($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=yU($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=yU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!ff($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class pU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await s1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!Q5(w))throw new a1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new a1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:VT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class rU{fileLoader=new Sf;envProcessor=new Cf;validator=new pU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)q0.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw q0.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Rw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let h=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(h)return T.push(c$(j,"package.json")),this.finalizeResult(h,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Uw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?t1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)q0.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)q0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?t1($,A,f):A,W=[c$(E1(),".config",$),c$(E1(),".config"),E1()];for(let J of W){if(f)q0.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)q0.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?t1($,Y,X):Y;try{let J=c$(A,"package.json");if(!DU(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)q0.success(`Configuration loaded from package.json: ${j}`);return{config:tU(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)q0.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:t1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Uw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return q1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);q1.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,c$($,"config"),c$($,".config"),w?c$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(c$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[c$(E1(),".config",$),c$(E1(),".config"),E1()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function tj($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function $K($){return l0.loadConfig({...$,__strictErrorHandling:!0})}async function MT($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await l0.loadConfig($);else Y=await l0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)q0.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await l0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function wK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await l0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&tj(A)))return(await l0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await l0.loadConfig({...$,cwd:$.cwd||Rw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&tj(w)))return(await l0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function AK($,w,A="replace"){let Y=new Sf;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function t1($,w,A=!1){let Y=new Cf,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((h)=>h.toUpperCase()).join("")}`,`${f}_${j.map((h)=>h.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let h of T)if(F=Rw.env[h],F!==void 0){H=h;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let h=Number(F);if(!Number.isNaN(h))J[B]=h}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((h)=>h.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function YK($){let w=c$(Rw.cwd(),$.configDir),A=c$(Rw.cwd(),$.generatedDir),Y=c$(A,"config-types.ts");if(!DU(_j(Y)))J5(_j(Y),{recursive:!0,mode:511});let f=DU(w)?W5(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${DK}
|
|
162
|
+
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
163
|
+
`;B5(Y,X,{mode:438})}function fK($){let w=null,A=null,Y=()=>{if(!A)A=MT($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)q0.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function XK($){let w=gj(k5.cwd(),$?.configDir||"./config");function A(){if(!_5(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=D5(w).filter((J)=>f.has(MU(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=MU(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=MU(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((B)=>B.base),U=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=f.length?`{
|
|
164
|
+
${f.map((B)=>{let E=gj(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${E}').default`}).join(`,
|
|
161
165
|
`)}
|
|
162
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
166
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${U}
|
|
163
167
|
export type ConfigByName = ${W}
|
|
164
168
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
165
169
|
export type ConfigOf = Config
|
|
166
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function M7($,w={}){let A=AU.cwd();while(A.includes("storage"))A=ZF(A,"..");let J=ZF(A,$||"");if(w?.relative)return R7(AU.cwd(),J);return J}function H$(){if(u0.env.NODE_ENV==="test"||u0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function k7(){if(u0.env.NODE_ENV==="test"||u0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u0<"u"){let $=u0.type;if($==="renderer"||$==="worker")return!1;return!!(u0.versions&&(u0.versions.node||u0.versions.bun))}return!1}class PF{async format($){let w=await k7(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:B1.pid,hostname:w(),environment:B1.env.NODE_ENV||"development",platform:B1.platform,version:B1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:B1.env.NODE_ENV||B1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...JU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new PF,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},J=w.timestamp!==void 0;if(J)delete A.timestamp;if(this.config={...this.config,...A,timestamp:J||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=U,this.keys.set(U,Y),this.encryptionKeys.set(U,{key:Y,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...$f,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$f};return{...$f,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:JU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!H$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await V7(this.config.logDirectory,FF.F_OK|FF.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await O7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b0.from($);try{if(!cJ(this.currentLogFile))await e8(this.currentLogFile,"",{mode:420});if(U=EF(this.currentLogFile,"a",420),S7(U,Z,{flag:"a"}),BF(U),U!==void 0)o8(U),U=void 0;if((await Z1(this.currentLogFile)).size===0){if(await e8(this.currentLogFile,Z,{flag:"w",mode:420}),(await Z1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<f-1){let F=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,F);let z=W*2**Y;await new Promise((j)=>setTimeout(j,z)),Y++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(U!==void 0)try{o8(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Z){if(Y===f-1){let E=Z,F=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),Z}Y++;let B=W*2**(Y-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(J,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return W1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return W1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return W1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},J)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),J=this.generateKey();this.currentKeyId=A,this.keys.set(A,J),this.encryptionKeys.set(A,{key:J,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Z])=>Z.createdAt.getTime()-W.createdAt.getTime()),Y=typeof w.maxKeys==="number"?w.maxKeys:1,f=Math.max(1,Y);if(U.length>f)for(let[W]of U.slice(f))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return s8(16).toString("hex")}generateKey(){return s8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=s8(16),J=y7("aes-256-gcm",w,A),U=b0.isBuffer($)?$:b0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),B=b0.allocUnsafe(16+W+16);return A.copy(B,0),Y.copy(B,16),f.copy(B,16+Y.length),Z.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let J=zF(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(b0.from(b0.concat(U)))),J.on("error",A),J.write($),J.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H$())return;if(!this.shouldWriteToFile())return;let $=await Z1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await uJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,B)=>{let E=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await Z1(A).catch(()=>null))try{if(await jF(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await vJ(W)}catch(Z){console.error("Error compressing rotated file:",Z)}if(Y.length===0&&!U.some((Z)=>Z.endsWith(".log.1")))try{let Z=`${A}.1`;await e8(Z,"")}catch(Z){console.error("Error creating backup file:",Z)}}catch(Z){console.error(`Error during rotation: ${Z instanceof Error?Z.message:String(Z)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),Y=A.replace(/\.log$/,`-${U}.log`);if(await Z1(A).catch(()=>null))await jF(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await uJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await vJ(W1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=WF($),J=L7(w),U=zF();await D7(A,U,J)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let J=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(J);console.log(J)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),cJ(this.currentLogFile))try{let $=EF(this.currentLogFile,"r+");BF($),o8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await uJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await vJ(W1(this.config.logDirectory,A))}catch(J){console.error(`Failed to delete temp file ${A}:`,J)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H$())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(j)=>j.replace(this.ANSI_PATTERN,"");if(!this.fancy){let j=[];if(f)j.push(w);if(Y==="warning")j.push("WARN");else if(Y==="error")j.push("ERROR");else if(A)j.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)j.push(J.replace(/[[\]]/g,""));return j.push(U),j.join(" ")}let Z=_.stdout.columns||120,B="";if(Y==="warning"||Y==="error")B=`${A} ${U}`;else if(Y==="info"||Y==="success")B=`${A} ${J} ${U}`;else B=`${A} ${J} ${i.cyan(U)}`;if(!f)return B.trim();let E=W(B).trim().length,F=W(w).length,z=Math.max(1,Z-2-E-F);return`${B.trim()}${" ".repeat(z)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(Y,f)=>{let W=Number.parseInt(f,10);return W<w[0].length?String(w[0][W]):Y});let A=/%([sdijfo%])/g,J=0,U=$.replace(A,(Y,f)=>{if(f==="%")return"%";if(J>=w.length)return Y;let W=w[J++];switch(f){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return Y}});if(J<w.length)U+=` ${w.slice(J).map((Y)=>typeof Y==="object"?JSON.stringify(Y,null,2):String(Y)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,U)=>{let Y=i.underline(i.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${Y}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${Y}\x1B]8;;\x1B\\`;return Y}),w=w.replace(/`([^`]+)`/g,(A,J)=>i.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>i.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>i.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>i.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>i.strikethrough(J)),w}supportsHyperlinks(){if(H$())return!1;let $=_.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=_.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(X7(w)||w.startsWith("./")||w.startsWith("../"))w=_7(w);else return null;return cJ(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let J=new Date,U=this.formatConsoleTimestamp(J),Y=this.formatFileTimestamp(J),f,W;if(w instanceof Error)f=w.message,W=w.stack;else f=this.formatMessage(w,A);let{consoleText:Z,fileText:B}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":i7[$],z=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:i.gray(Z),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"success":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:i.green(Z),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:U,icon:F,tag:z,message:Z,level:$}),console.error(j),W){let G=W.split(`
|
|
167
|
-
`);for(let
|
|
170
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function PK($,w={}){let A=Mf.cwd();while(A.includes("storage"))A=fT(A,"..");let Y=fT(A,$||"");if(w?.relative)return xK(Mf.cwd(),Y);return Y}function H$(){if(d0.env.NODE_ENV==="test"||d0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tK(){if(d0.env.NODE_ENV==="test"||d0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof d0<"u"){let $=d0.type;if($==="renderer"||$==="worker")return!1;return!!(d0.versions&&(d0.versions.node||d0.versions.bun))}return!1}class kT{async format($){let w=await tK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:R1.pid,hostname:w(),environment:R1.env.NODE_ENV||"development",platform:R1.platform,version:R1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R1.env.NODE_ENV||R1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...If},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new kT,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{..._U,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{..._U};return{..._U,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:If.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!H$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await vK(this.config.logDirectory,WT.F_OK|WT.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await mK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:n0.from($);try{if(!Uf(this.currentLogFile))await QU(this.currentLogFile,"",{mode:420});if(f=JT(this.currentLogFile,"a",420),nK(f,J,{flag:"a"}),UT(f),f!==void 0)VU(f),f=void 0;if((await G1(this.currentLogFile)).size===0){if(await QU(this.currentLogFile,J,{flag:"w",mode:420}),(await G1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{VU(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 K1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return K1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return K1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return OU(16).toString("hex")}generateKey(){return OU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=OU(16),Y=bK("aes-256-gcm",w,A),f=n0.isBuffer($)?$:n0.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=n0.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=ET(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(n0.from(n0.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H$())return;if(!this.shouldWriteToFile())return;let $=await G1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Jf(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await G1(A).catch(()=>null))try{if(await BT(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Wf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await QU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await G1(A).catch(()=>null))await BT(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await Jf(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Wf(K1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=XT($),Y=uK(w),f=ET();await gK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),Uf(this.currentLogFile))try{let $=JT(this.currentLogFile,"r+");UT($),VU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await Jf(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Wf(K1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H$())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=_.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${b.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=b.underline(b.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>b.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>b.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>b.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>b.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>b.strikethrough(Y)),w}supportsHyperlinks(){if(H$())return!1;let $=_.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=_.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(dK(w)||w.startsWith("./")||w.startsWith("../"))w=lK(w);else return null;return Uf(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":oK[$],T=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
171
|
+
`);for(let h of H)if(h.trim()&&!h.includes(U))console.error(this.formatConsoleMessage({timestamp:f,message:b.gray(` ${h}`),level:$,showTimestamp:!1}))}break}}else if(!H$()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let E=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
168
172
|
`;if(W)E+=`${W}
|
|
169
|
-
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,
|
|
170
|
-
`);if(this[
|
|
171
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?
|
|
172
|
-
`),
|
|
173
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
174
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),
|
|
175
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H$()||!_.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await uJ(this.config.logDirectory),A=[];for(let J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let Y=W1(this.config.logDirectory,J);if($.before)try{if((await Z1(Y)).mtime>=$.before)continue}catch(f){console.error(`Failed to get stats for file ${Y}:`,f);continue}A.push(Y)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let J of A)try{await vJ(J),console.warn(`Deleted log file: ${J}`)}catch(U){console.error(`Failed to delete log file ${J}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var n2,m2=($)=>$,g2=($,w)=>{for(var A in w)n2($,A,{get:w[A],enumerable:!0,configurable:!0,set:d2.bind(w,A)})},l2=($,w)=>()=>($&&(w=$($=0)),w),GF,SF,E1,c1,VF,lh,ph,sE,mJ,Uf,L$,p,th,oE,rh,eE,ah,sh,p8,oh,$F,wF,t8,eh,$7,w7,A7,dJ,OF,J7,S$,U7,Y7,AF,gJ,Yf,z$,Q,f7,JF,Z7,UF,W7,B7,r8,E7,YF,fF,F7,a8,j7,z7,H7,T7,G7,lJ,XF,h7,q7="0.15.6",r$,$U,b1,ff,Zf,wU,Wf,Bf,i1,Ef,Ff,$w,_F,DF,H0,v0,kF,QF,N7,I7,xF,JU,FI,q$,i,MI,Q7,II,x7,yI,CI,HF,LI,P7,b7,SI,TF,VI,OI,XI,_I,DI,$f,i7,kI;var Nf=X$(()=>{n2=Object.defineProperty;GF={};g2(GF,{withErrorRecovery:()=>RF,tryLoadConfig:()=>nh,loadConfigWithResult:()=>uh,loadConfig:()=>LF,isRetryableError:()=>Qh,isConfigNotFoundError:()=>kh,isBunfigError:()=>MF,globalPerformanceMonitor:()=>c1,globalCache:()=>E1,getEnvOrDefault:()=>xh,generateConfigTypes:()=>mh,defaultGeneratedDir:()=>QF,defaultConfigDir:()=>kF,deepMergeWithArrayStrategy:()=>Gf,deepMerge:()=>IF,createLibraryConfig:()=>dh,config:()=>vh,bunfigPlugin:()=>gh,applyEnvVarsToConfig:()=>x1,TypeGenerationError:()=>Bf,SchemaValidationError:()=>i1,PluginError:()=>Ff,PerformanceMonitor:()=>zf,FileSystemError:()=>Wf,ErrorFactory:()=>$w,EnvVarError:()=>wU,EnvProcessor:()=>UU,ConfigValidator:()=>hf,ConfigValidationError:()=>ff,ConfigNotFoundError:()=>$U,ConfigMergeError:()=>Zf,ConfigLoader:()=>qf,ConfigLoadError:()=>b1,ConfigFileLoader:()=>YU,ConfigCache:()=>jf,CacheUtils:()=>VF,BunfigError:()=>r$,BrowserConfigError:()=>Ef,ArrayMergeStrategies:()=>_F});N7=l2(async()=>{SF=import.meta.require,E1=new jf,c1=new zf,VF={createKey:Kh,isEquivalent:Rh,estimateMemoryUsage:Mh},lh=rJ(Af.cwd(),"config"),ph=rJ(Af.cwd(),"src/generated"),sE=tJ.env.CLARITY_LOG_DIR||o2(Ch(),"logs"),mJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Uf=await Lh(),L$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},p=L$,th=L$.red,oE=L$.green,rh=L$.yellow,eE=L$.blue,ah=L$.magenta,sh=L$.cyan,p8=L$.white,oh=L$.gray,$F=L$.bgRed,wF=L$.bgYellow,t8=L$.bold,eh=L$.dim,$7=L$.italic,w7=L$.underline,A7=L$.reset,dJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},OF={debug:"\uD83D\uDD0D",info:eE("ℹ"),success:oE("✓"),warning:wF(p8(t8(" WARN "))),error:$F(p8(t8(" ERROR ")))},J7=new sJ("stacks"),S$=new sJ("bunfig",{showTags:!0}),U7=P$(P1.cwd(),"config"),Y7=P$(P1.cwd(),"src/generated"),AF=pJ.env.CLARITY_LOG_DIR||a2(Xh(),"logs"),gJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:AF,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Yf=await _h(),z$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Q=z$,f7=z$.red,JF=z$.green,Z7=z$.yellow,UF=z$.blue,W7=z$.magenta,B7=z$.cyan,r8=z$.white,E7=z$.gray,YF=z$.bgRed,fF=z$.bgYellow,F7=z$.bgGray,a8=z$.bold,j7=z$.dim,z7=z$.italic,H7=z$.underline,T7=z$.strikethrough,G7=z$.reset,lJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},XF={debug:"\uD83D\uDD0D",info:UF("ℹ"),success:JF("✓"),warning:fF(r8(a8(" WARN "))),error:YF(r8(a8(" ERROR ")))},h7=new eJ("stacks"),r$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,J])=>`${A}: ${J}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},$U=class extends r${code="CONFIG_NOT_FOUND";constructor(w,A,J){let U=J?` or alias "${J}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},b1=class extends r${code="CONFIG_LOAD_ERROR";constructor(w,A,J){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:J,originalError:A.name,originalMessage:A.message});this.cause=A}},ff=class extends r${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},Zf=class extends r${code="CONFIG_MERGE_ERROR";constructor(w,A,J,U){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:U,originalError:J.name,originalMessage:J.message});this.cause=J}},wU=class extends r${code="ENV_VAR_ERROR";constructor(w,A,J,U){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:U})}},Wf=class extends r${code="FILE_SYSTEM_ERROR";constructor(w,A,J){super(`File system ${w} failed for "${A}": ${J.message}`,{operation:w,path:A,originalError:J.name,originalMessage:J.message});this.cause=J}},Bf=class extends r${code="TYPE_GENERATION_ERROR";constructor(w,A,J){super(`Failed to generate types from "${w}" to "${A}": ${J.message}`,{configDir:w,outputPath:A,originalError:J.name,originalMessage:J.message});this.cause=J}},i1=class extends r${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,J){super(`Schema validation failed${J?` for config "${J}"`:""}`,{schemaPath:w,configName:J,validationErrors:A,errorCount:A.length})}},Ef=class extends r${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,U){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:U})}},Ff=class extends r${code="PLUGIN_ERROR";constructor(w,A,J){super(`Plugin "${w}" failed during ${A}: ${J.message}`,{pluginName:w,operation:A,originalError:J.name,originalMessage:J.message});this.cause=J}},$w={configNotFound($,w,A){return new $U($,w,A)},configLoad($,w,A){return new b1($,w,A)},configValidation($,w,A){return new ff($,w,A)},configMerge($,w,A,J){return new Zf($,w,A,J)},envVar($,w,A,J){return new wU($,w,A,J)},fileSystem($,w,A){return new Wf($,w,A)},typeGeneration($,w,A){return new Bf($,w,A)},schemaValidation($,w,A){return new i1($,w,A)},browserConfig($,w,A,J){return new Ef($,w,A,J)},plugin($,w,A){return new Ff($,w,A)}},_F={replace:"replace",concat:"concat",smart:"smart"},DF=/^https?:\/\//,H0=new eJ("bunfig",{showTags:!0}),v0=new qf,kF=b$(jw.cwd(),"config"),QF=b$(jw.cwd(),"src/generated")});I7=AU.env.CLARITY_LOG_DIR||K7(M7(),"logs"),xF={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},JU={...xF},FI=(async()=>{try{let{loadConfig:$}=await N7().then(()=>GF),w=await $({name:"clarity",alias:"logging",defaultConfig:xF,cwd:AU.cwd()});if(w)Object.assign(JU,w)}catch{}return JU})();q$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=q$,MI=q$.red,Q7=q$.green,II=q$.yellow,x7=q$.blue,yI=q$.magenta,CI=q$.cyan,HF=q$.white,LI=q$.gray,P7=q$.bgRed,b7=q$.bgYellow,SI=q$.bgGray,TF=q$.bold,VI=q$.dim,OI=q$.italic,XI=q$.underline,_I=q$.strikethrough,DI=q$.reset,$f={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},i7={debug:"\uD83D\uDD0D",info:x7("ℹ"),success:Q7("✓"),warning:b7(HF(TF(" WARN "))),error:P7(HF(TF(" ERROR ")))};kI=new zw("stacks")});var F1={};UZ(F1,{safeStringify:()=>J0,safeDeleteFile:()=>Mf,resolvePathRewrite:()=>Rf,redactSensitive:()=>fU,isValidRootCA:()=>Kf,isSingleProxyOptions:()=>v1,isSingleProxyConfig:()=>d7,isMultiProxyOptions:()=>Tw,isMultiProxyConfig:()=>uF,getSudoPassword:()=>Hw,getPrimaryDomain:()=>ZU,extractHostname:()=>m7,execSudoSync:()=>u1,debugLog:()=>H});import{execSync as bF}from"node:child_process";import*as cF from"node:fs/promises";function Hw(){return process.env.SUDO_PASSWORD}function u1($){let w=Hw(),A=$.replace(/'/g,"'\\''");if(w)return bF(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return bF(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function H($,w,A){if(A)c7.debug(`[rpx:${$}] ${w}`)}function n7($){let w=$.toLowerCase();return u7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function fU($){if(Array.isArray($))return $.map((A)=>fU(A));if(typeof $==="string")return v7.test($)?iF:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(n7(A)){w[A]=iF;continue}w[A]=fU(J)}return w}function J0($,w){return JSON.stringify(fU($),null,w)}function m7($){if(Tw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(v1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function Kf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function ZU($){if(!$)return"stacks.localhost";if(Tw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(v1($))return $.to||"stacks.localhost";return"stacks.localhost"}function uF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Tw($){return"proxies"in $&&Array.isArray($.proxies)}function v1($){return"to"in $&&typeof $.to==="string"}function d7($){return!!($&&("to"in $)&&!("proxies"in $))}function Rf($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let J=A.to.startsWith("http")?new URL(A.to).host:A.to,U=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:J,targetPath:U}}return null}async function Mf($,w){try{await cF.unlink($),H("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")H("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var c7,iF="[redacted]",u7,v7;var Y$=X$(()=>{Nf();c7=new zw("rpx",{showTags:!1});u7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),v7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as WU}from"node:child_process";import{homedir as g7}from"node:os";import{join as l7}from"node:path";function BU(){return l7(g7(),"Library/Keychains/login.keychain-db")}function yf(){return[z1,BU()]}function vF($,w=If){let A=WU(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),J=[];for(let U of A.split(`
|
|
176
|
-
`)){let
|
|
177
|
-
`))if(
|
|
173
|
+
`;if(E=E.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(E)}progress($,w=""){let A={update:(W,J)=>{},finish:(W)=>{},interrupt:(W,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!H$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!H$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,J="info")=>{if(!H$()&&_.stdout.isTTY)_.stdout.write(`
|
|
174
|
+
`);if(this[J==="warning"?"warn":J](W),this.activeProgressBar&&this.shouldStyleConsole()&&!H$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:A,message:`${b.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),f=Math.round(Y-w),X=`${$} completed in ${f}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${X}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
|
|
175
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:E,message:`${X}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!H$())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new qw(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(H$())throw Error("createReadStream is not supported in browser environments");if(!Uf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return XT(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=n0.isBuffer($)?$:n0.from($,"base64"),f=Y.subarray(0,16),X=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=cK("aes-256-gcm",A,f);W.setAuthTag(X);let J=W.update(U),B=W.final(),E=J.length+B.length,j=n0.allocUnsafe(E);return J.copy(j,0),B.copy(j,J.length),j.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H$()}isServerMode(){return!H$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:f,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=f.split(`
|
|
176
|
+
`),J=Math.max(...W.map((T)=>T.length))+2,B=`┌${"─".repeat(J)}┐`,E=`└${"─".repeat(J)}┘`,j=W.map((T)=>{return this.formatConsoleMessage({timestamp:A,message:b.cyan(T),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(B),showTimestamp:!1})),j.forEach((T)=>console.error(T)),console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(E),showTimestamp:!1}))}else if(!H$())console.error(`${Y} ${this.environment}.INFO: [BOX] ${X}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${X}
|
|
177
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(H$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let f=Y.toString().trim().toLowerCase();_.stdin.removeListener("data",A);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),w(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,B=0;if(A=$.replace(J,(E,j)=>{if(j==="%")return"%";if(B>=w.length)return E;let T=w[B++];switch(j){case"s":return String(T);case"d":case"i":return Number(T).toString();case"j":case"o":return JSON.stringify(T,null,2);default:return E}}),B<w.length)A+=` ${w.slice(B).map((E)=>typeof E==="object"?JSON.stringify(E,null,2):String(E)).join(" ")}`}let{consoleText:Y,fileText:f}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${B}${J} ${b.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
178
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),f=$.barLength-Y,X=b.green("━".repeat(Y)),U=b.gray("━".repeat(f)),W=`[${X}${U}]`,J=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",E=this.options.showIcons===!1?"":w||A===100?b.green("✓"):b.blue("▶"),j=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",T=`\r${E}${j} ${W} ${J}${B}`,F=_.stdout.columns||80,H=" ".repeat(Math.max(0,F-T.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${T}${H}`,_.stdout.write($.lastRenderedLine),w)_.stdout.write(`
|
|
179
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H$()||!_.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await Jf(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=K1(this.config.logDirectory,Y);if($.before)try{if((await G1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await Wf(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var A5,Y5=($)=>$,X5=($,w)=>{for(var A in w)A5($,A,{get:w[A],enumerable:!0,configurable:!0,set:f5.bind(w,A)})},U5=($,w)=>()=>($&&(w=$($=0)),w),FT,IT,q1,s1,CT,UK,JK,pj,Ef,xU,V$,t,WK,rj,BK,aj,EK,jK,IU,TK,sj,oj,CU,FK,zK,hK,HK,jf,ST,GK,Q$,KK,RK,ej,Tf,PU,h$,Z,qK,$T,NK,wT,yK,MK,SU,IK,AT,YT,CK,LU,SK,LK,OK,VK,QK,Ff,LT,_K,DK="0.15.6",o$,Nf,r1,iU,bU,yf,cU,uU,a1,nU,vU,Uw,OT,VT,q0,l0,QT,_T,kK,iK,DT,If,rI,N$,b,UC,pK,JC,rK,WC,BC,jT,EC,aK,sK,jC,TT,TC,FC,zC,hC,HC,_U,oK,GC;var aU=K$(()=>{A5=Object.defineProperty;FT={};X5(FT,{withErrorRecovery:()=>KT,tryLoadConfig:()=>AK,loadConfigWithResult:()=>$K,loadConfig:()=>MT,isRetryableError:()=>p5,isConfigNotFoundError:()=>t5,isBunfigError:()=>RT,globalPerformanceMonitor:()=>s1,globalCache:()=>q1,getEnvOrDefault:()=>r5,generateConfigTypes:()=>YK,defaultGeneratedDir:()=>_T,defaultConfigDir:()=>QT,deepMergeWithArrayStrategy:()=>tU,deepMerge:()=>qT,createLibraryConfig:()=>fK,config:()=>wK,bunfigPlugin:()=>XK,applyEnvVarsToConfig:()=>t1,TypeGenerationError:()=>uU,SchemaValidationError:()=>a1,PluginError:()=>vU,PerformanceMonitor:()=>dU,FileSystemError:()=>cU,ErrorFactory:()=>Uw,EnvVarError:()=>yf,EnvProcessor:()=>Cf,ConfigValidator:()=>pU,ConfigValidationError:()=>iU,ConfigNotFoundError:()=>Nf,ConfigMergeError:()=>bU,ConfigLoader:()=>rU,ConfigLoadError:()=>r1,ConfigFileLoader:()=>Sf,ConfigCache:()=>mU,CacheUtils:()=>CT,BunfigError:()=>o$,BrowserConfigError:()=>nU,ArrayMergeStrategies:()=>OT});kK=U5(async()=>{IT=import.meta.require,q1=new mU,s1=new dU,CT={createKey:Z5,isEquivalent:x5,estimateMemoryUsage:P5},UK=Hf(kU.cwd(),"config"),JK=Hf(kU.cwd(),"src/generated"),pj=hf.env.CLARITY_LOG_DIR||T5(c5(),"logs"),Ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},xU=await u5(),V$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},t=V$,WK=V$.red,rj=V$.green,BK=V$.yellow,aj=V$.blue,EK=V$.magenta,jK=V$.cyan,IU=V$.white,TK=V$.gray,sj=V$.bgRed,oj=V$.bgYellow,CU=V$.bold,FK=V$.dim,zK=V$.italic,hK=V$.underline,HK=V$.reset,jf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ST={debug:"\uD83D\uDD0D",info:aj("ℹ"),success:rj("✓"),warning:oj(IU(CU(" WARN "))),error:sj(IU(CU(" ERROR ")))},GK=new Kf("stacks"),Q$=new Kf("bunfig",{showTags:!0}),KK=b$(p1.cwd(),"config"),RK=b$(p1.cwd(),"src/generated"),ej=zf.env.CLARITY_LOG_DIR||E5(d5(),"logs"),Tf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ej,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PU=await l5(),h$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Z=h$,qK=h$.red,$T=h$.green,NK=h$.yellow,wT=h$.blue,yK=h$.magenta,MK=h$.cyan,SU=h$.white,IK=h$.gray,AT=h$.bgRed,YT=h$.bgYellow,CK=h$.bgGray,LU=h$.bold,SK=h$.dim,LK=h$.italic,OK=h$.underline,VK=h$.strikethrough,QK=h$.reset,Ff={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},LT={debug:"\uD83D\uDD0D",info:wT("ℹ"),success:$T("✓"),warning:YT(SU(LU(" WARN "))),error:AT(SU(LU(" ERROR ")))},_K=new qf("stacks"),o$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},Nf=class extends o${code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},r1=class extends o${code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},iU=class extends o${code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},bU=class extends o${code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},yf=class extends o${code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},cU=class extends o${code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},uU=class extends o${code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},a1=class extends o${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},nU=class extends o${code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},vU=class extends o${code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Uw={configNotFound($,w,A){return new Nf($,w,A)},configLoad($,w,A){return new r1($,w,A)},configValidation($,w,A){return new iU($,w,A)},configMerge($,w,A,Y){return new bU($,w,A,Y)},envVar($,w,A,Y){return new yf($,w,A,Y)},fileSystem($,w,A){return new cU($,w,A)},typeGeneration($,w,A){return new uU($,w,A)},schemaValidation($,w,A){return new a1($,w,A)},browserConfig($,w,A,Y){return new nU($,w,A,Y)},plugin($,w,A){return new vU($,w,A)}},OT={replace:"replace",concat:"concat",smart:"smart"},VT=/^https?:\/\//,q0=new qf("bunfig",{showTags:!0}),l0=new rU,QT=c$(Rw.cwd(),"config"),_T=c$(Rw.cwd(),"src/generated")});iK=Mf.env.CLARITY_LOG_DIR||ZK(PK(),"logs"),DT={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:iK,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},If={...DT},rI=(async()=>{try{let{loadConfig:$}=await kK().then(()=>FT),w=await $({name:"clarity",alias:"logging",defaultConfig:DT,cwd:Mf.cwd()});if(w)Object.assign(If,w)}catch{}return If})();N$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=N$,UC=N$.red,pK=N$.green,JC=N$.yellow,rK=N$.blue,WC=N$.magenta,BC=N$.cyan,jT=N$.white,EC=N$.gray,aK=N$.bgRed,sK=N$.bgYellow,jC=N$.bgGray,TT=N$.bold,TC=N$.dim,FC=N$.italic,zC=N$.underline,hC=N$.strikethrough,HC=N$.reset,_U={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oK={debug:"\uD83D\uDD0D",info:rK("ℹ"),success:pK("✓"),warning:sK(jT(TT(" WARN "))),error:aK(jT(TT(" ERROR ")))};GC=new qw("stacks")});var N1={};nJ(N1,{safeStringify:()=>J0,safeDeleteFile:()=>eU,resolvePathRewrite:()=>oU,redactSensitive:()=>Lf,isValidRootCA:()=>sU,isSingleProxyOptions:()=>e1,isSingleProxyConfig:()=>f6,isMultiProxyOptions:()=>yw,isMultiProxyConfig:()=>iT,getSudoPassword:()=>Nw,getPrimaryDomain:()=>Of,extractHostname:()=>Y6,execSudoSync:()=>o1,debugLog:()=>z});import{execSync as ZT}from"node:child_process";import*as PT from"node:fs/promises";function Nw(){return process.env.SUDO_PASSWORD}function o1($){let w=Nw(),A=$.replace(/'/g,"'\\''");if(w)return ZT(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return ZT(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function z($,w,A){if(A)eK.debug(`[rpx:${$}] ${w}`)}function A6($){let w=$.toLowerCase();return $6.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function Lf($){if(Array.isArray($))return $.map((A)=>Lf(A));if(typeof $==="string")return w6.test($)?xT:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(A6(A)){w[A]=xT;continue}w[A]=Lf(Y)}return w}function J0($,w){return JSON.stringify(Lf($),null,w)}function Y6($){if(yw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(e1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function sU($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function Of($){if(!$)return"stacks.localhost";if(yw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(e1($))return $.to||"stacks.localhost";return"stacks.localhost"}function iT($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function yw($){return"proxies"in $&&Array.isArray($.proxies)}function e1($){return"to"in $&&typeof $.to==="string"}function f6($){return!!($&&("to"in $)&&!("proxies"in $))}function oU($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let Y=A.to.startsWith("http")?new URL(A.to).host:A.to,f=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:Y,targetPath:f}}return null}async function eU($,w){try{await PT.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var eK,xT="[redacted]",$6,w6;var X$=K$(()=>{aU();eK=new qw("rpx",{showTags:!1});$6=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),w6=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as Vf}from"node:child_process";import{homedir as X6}from"node:os";import{join as U6}from"node:path";function Qf(){return U6(X6(),"Library/Keychains/login.keychain-db")}function wJ(){return[M1,Qf()]}function bT($,w=$J){let A=Vf(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),Y=[];for(let f of A.split(`
|
|
180
|
+
`)){let X=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(X)Y.push(X[1].toUpperCase())}return Y}function AJ($){if(process.platform!=="darwin")return;let w=sY($.caPath);if(!w)return;let A=$.commonName??$J,Y=$.keychains??wJ();for(let f of Y)for(let X of bT(f,A)){if(X===w)continue;try{if(f.startsWith("/Library"))o1(`security delete-certificate -Z ${X} "${f}"`);else Vf(`security delete-certificate -Z ${X} "${f}"`,{stdio:"ignore"});z("ssl",`Removed stale Root CA ${X} from ${f}`,$.verbose)}catch{}}}function YJ($,w,A){if(process.platform!=="darwin")return _f($,A);try{let f=Vf(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return z("ssl",`verify-cert ${w}: ${f?"trusted":"not trusted"}`,A?.verbose),f}catch{return!1}}function _f($,w){let A=sY($);if(!A)return!1;for(let Y of wJ())try{let f=Vf(`security find-certificate -a -Z "${Y}" 2>/dev/null || true`,{encoding:"utf8"});for(let X of f.split(`
|
|
181
|
+
`))if(X.toUpperCase().includes("SHA-256")){if(X.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return z("ssl",`Root CA fingerprint found in ${Y}`,w?.verbose),!0}}catch{}return!1}var y1="-d -r trustRoot -p ssl -p basic",M1="/Library/Keychains/System.keychain",$J="rpx.localhost";var fJ=K$(()=>{FU();X$()});import{execSync as I1}from"node:child_process";import G$ from"node:fs/promises";import*as XJ from"node:os";import{homedir as Df}from"node:os";import{join as D$}from"node:path";import*as Jw from"node:process";function nT($){return{caCertPath:D$($,W6),caKeyPath:D$($,B6)}}async function E6($,w){try{let[A,Y]=await Promise.all([G$.readFile($.caCertPath,"utf8"),G$.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!Y.includes("PRIVATE KEY-----"))return z("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:Y}}catch(A){return z("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function cT($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function vT($){let A=Of($).replace(/\*/g,"wildcard"),Y=D$(Df(),".stacks","ssl"),f=Y;if(typeof $?.https==="object")return f=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:Y,{caCertPath:$.https.caCertPath||D$(f,`${A}.ca.crt`),certPath:$.https.certPath||D$(f,`${A}.crt`),keyPath:$.https.keyPath||D$(f,`${A}.key`)};return{caCertPath:D$(f,`${A}.ca.crt`),certPath:D$(f,`${A}.crt`),keyPath:D$(f,`${A}.key`)}}function uT($){let w=new Set;if(yw($))$.proxies.forEach((A)=>{let Y=A.to||"rpx.localhost";cT(Y).forEach((f)=>w.add(f))});else if(e1($)){let A=$.to||"rpx.localhost";cT(A).forEach((Y)=>w.add(Y))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function C1($){if(Ww&&!$.forceRegenerate){z("ssl","Using cached SSL configuration",$.verbose);return}j6();let w=yw($)?$.proxies.map((E)=>E.to):[$.to];z("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=$A($,$.verbose),Y=A.basePath||D$(Df(),".stacks","ssl");await G$.mkdir(Y,{recursive:!0});let f=nT(Y),X=await E6(f,$.verbose),U=!1;if(!X){if($.verbose)q.info("Generating Root CA certificate (one-time)...");X=await XU(A);try{await Promise.all([G$.writeFile(f.caCertPath,X.certificate),G$.writeFile(f.caKeyPath,X.privateKey,{mode:384})]),U=!0,z("ssl",`Persisted Root CA at ${f.caCertPath}`,$.verbose)}catch(E){throw z("ssl",`Error saving Root CA files: ${E}`,$.verbose),Error(`Failed to save Root CA files: ${E}`)}}else z("ssl",`Reusing existing Root CA from ${f.caCertPath}`,$.verbose);if($.verbose)q.info(`Generating host certificate for: ${w.join(", ")}`);let W=await UU({...A,rootCA:{certificate:X.certificate,privateKey:X.privateKey}});try{await Promise.all([G$.writeFile(A.certPath,W.certificate),G$.writeFile(A.keyPath,W.privateKey),G$.writeFile(A.caCertPath,X.certificate)]),z("ssl","Certificate files saved successfully",$.verbose)}catch(E){throw z("ssl",`Error saving certificate files: ${E}`,$.verbose),Error(`Failed to save certificate files: ${E}`)}if(U?!1:await dT(f.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(z("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)q.success("Root CA is already trusted in system trust store");if(Ww={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)q.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(Jw.platform==="darwin")try{AJ({caPath:f.caCertPath,verbose:$.verbose});let E=Qf();try{I1(`security add-trusted-cert ${y1} -k "${E}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(o1(`security add-trusted-cert ${y1} -k ${M1} "${f.caCertPath}"`),$.verbose)q.success("Successfully added Root CA to system trust store");B=!0;let j=D$(Y,"trust-rpx-cert.sh"),T=`#!/bin/bash
|
|
178
182
|
echo "Trusting RPX Root CA"
|
|
179
|
-
sudo security add-trusted-cert ${
|
|
183
|
+
sudo security add-trusted-cert ${y1} -k ${M1} "${f.caCertPath}"
|
|
180
184
|
echo "Root CA trusted! Please restart your browser."
|
|
181
185
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
182
|
-
`;await
|
|
186
|
+
`;await G$.writeFile(j,T,{mode:493})}catch(E){if($.verbose)q.warn(`Could not add Root CA to trust store automatically: ${E}`);let j=D$(Y,"trust-rpx-cert.sh"),T=`#!/bin/bash
|
|
183
187
|
echo "Trusting RPX Root CA"
|
|
184
|
-
sudo security add-trusted-cert ${
|
|
188
|
+
sudo security add-trusted-cert ${y1} -k ${M1} "${f.caCertPath}"
|
|
185
189
|
echo "Root CA trusted! Please restart your browser."
|
|
186
190
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
187
|
-
`;if(await
|
|
191
|
+
`;if(await G$.writeFile(j,T,{mode:493}),$.verbose)q.info(`Created a trust helper script at: ${j}`),q.info(`If you're still having certificate issues, run: sh ${j}`)}else if(Jw.platform==="linux")try{let{exec:E}=await import("node:child_process"),j="/usr/local/share/ca-certificates/rpx",T=`
|
|
188
192
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
189
|
-
cp "${
|
|
193
|
+
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
190
194
|
update-ca-certificates
|
|
191
195
|
echo "RPX Root CA installed. Please restart your browser."
|
|
192
|
-
`,
|
|
193
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${
|
|
196
|
+
`,F=D$(XJ.tmpdir(),`rpx-trust-${Date.now()}.sh`);await G$.writeFile(F,T,{mode:493}),await new Promise((H)=>{E(`sudo bash "${F}"`,(h)=>{if(h){if($.verbose)q.warn(`Could not trust certificates: ${h}`);H(!1)}else{if($.verbose)q.success("Successfully added certificates to system trust store");H(!0)}})}),await G$.unlink(F).catch(()=>{}),B=!0}catch(E){if($.verbose)q.warn(`Failed to trust certificates: ${E}`)}else if(Jw.platform==="win32")try{let E=`
|
|
197
|
+
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
194
198
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
195
199
|
$store.Open("ReadWrite")
|
|
196
200
|
$store.Add($cert)
|
|
197
201
|
$store.Close()
|
|
198
202
|
Write-Host "Root CA trusted successfully!"
|
|
199
|
-
`,F=V$(Vf.tmpdir(),"rpx-trust.ps1");if(await T$.writeFile(F,E),H1(`powershell -ExecutionPolicy Bypass -File "${F}"`),$.verbose)K.success("Successfully added certificate to Windows trust store");B=!0}catch(E){if($.verbose)K.warn(`Could not trust certificate: ${E}`)}else try{await _8(W,Y.certificate,A),B=!0}catch(E){if($.verbose)K.warn(`Could not add certificate to trust store: ${E}`)}if(Aw={key:W.privateKey,cert:W.certificate,ca:Y.certificate},$.verbose)K.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)K.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),K.warn("This will bypass the warning and you should only need to do it once")}function s7(){Aw=null}async function n0($){if(!$)return null;if(Aw)return Aw;let w=n1($);try{let[A,J,U]=await Promise.all([T$.access(w.keyPath).then(()=>!0).catch(()=>!1),T$.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?T$.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!J)return H("ssl",`Certificate files don't exist: key=${A}, cert=${J}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let Y="regenerateUntrustedCerts"in $,f=$.regenerateUntrustedCerts,W=Y?f!==!1:!0;H("ssl",`Trust check: hasFlag=${Y}, flagValue=${f}, shouldCheckTrust=${W}`,$.verbose);let Z=w.basePath||V$(FU(),".stacks","ssl"),B=dF(Z);if(!(W?await pF(B.caCertPath,$):!0))return H("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[F,z,j]=await Promise.all([T$.readFile(w.keyPath,"utf8"),T$.readFile(w.certPath,"utf8"),U&&w.caCertPath?T$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(j&&!j.includes("-----BEGIN CERTIFICATE-----"))return H("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Tw($))try{let{X509Certificate:G}=await import("node:crypto"),h=new G(z).subjectAltName||"",N=$.proxies.map((R)=>R.to).filter((R)=>!h.includes(`DNS:${R}`));if(N.length>0)return H("ssl",`Certificate missing SANs for: ${N.join(", ")}, will regenerate`,$.verbose),null}catch(G){H("ssl",`Could not verify cert SANs: ${G}`,$.verbose)}return H("ssl","Successfully loaded existing certificates",$.verbose),Aw={key:F,cert:z,ca:j},Aw}catch(A){return H("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function n1($,w){let A=ZU($);H("ssl",`Primary domain: ${A}`,w);let J=gF($),U=V$(FU(),".stacks","ssl");if(typeof $.https==="object"){let Y=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:U,f={domain:A,hostCertCN:A,basePath:Y,caCertPath:$.https.caCertPath||J.caCertPath,certPath:$.https.certPath||J.certPath,keyPath:$.https.keyPath||J.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(mF($)).map((W)=>({type:2,value:W}))};if(Kf($.https.rootCA))f.rootCA=$.https.rootCA;return f}return{domain:A,hostCertCN:A,basePath:U,...J,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(mF($)).map((Y)=>({type:2,value:Y}))}}async function lF($,w){let A=gF({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];H("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((U)=>Mf(U,w)))}async function pF($,w){try{if(H("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),ww.platform==="darwin"){if(w?.serverName)return Lf($,w.serverName,{verbose:w.verbose});return EU($,{verbose:w.verbose})}else if(ww.platform==="win32")try{let J=H1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return H("ssl","Could not extract certificate subject",w?.verbose),!1;let U=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${J}*' } | Select-Object Subject"`;if(H1(U).toString().includes(J))return H("ssl","Certificate found in trusted root store",w?.verbose),!0;return H("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return H("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(ww.platform==="linux")try{let J=H1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",U=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let Y of U)try{if(H1(`find ${Y} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return H("ssl",`Certificate fingerprint found in ${Y}`,w?.verbose),!0}catch{}return H("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return H("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return H("ssl",`Platform ${ww.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return H("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var Aw=null,t7="rpx-root-ca.crt",r7="rpx-root-ca.key";var jU=X$(()=>{XE();r0();x8();Sf();Y$();Sf();P8()});function m1($,w){return async(A)=>{let J=new URL(A.url),Y=(A.headers.get("host")||"").split(":")[0],f=$(Y);if(!f)return H("request",`No route found for host: ${Y}`,w),new Response(`No proxy configured for ${Y}`,{status:404});let W=f.sourceHost,Z=J.pathname,B=Rf(J.pathname,f.pathRewrites);if(B)W=B.targetHost,Z=B.targetPath,H("request",`Path rewrite: ${J.pathname} → ${W}${Z}`,w);let E=`http://${W}${Z}${J.search}`;try{let F=new Headers(A.headers);if(F.set("host",W),f.changeOrigin)F.set("origin",`http://${f.sourceHost}`);F.set("x-forwarded-for","127.0.0.1"),F.set("x-forwarded-proto","https"),F.set("x-forwarded-host",Y);let z=await fetch(E,{method:A.method,headers:F,body:A.body,redirect:"manual"});if(f.cleanUrls&&J.pathname.endsWith(".html")){let G=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:G}})}let j=new Headers(z.headers);return new Response(z.body,{status:z.status,statusText:z.statusText,headers:j})}catch(F){return H("request",`Proxy error for ${Y}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}}}var zU=X$(()=>{Y$();Y$()});import*as HU from"node:fs";import*as i$ from"node:fs/promises";import{homedir as o7}from"node:os";import*as Of from"node:path";import*as TU from"node:process";function Jw(){return Of.join(o7(),".stacks","rpx","registry.d")}function d1($){return typeof $==="string"&&$.length>0&&$.length<=128&&e7.test($)}function Xf($,w){if(!d1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return Of.join($,`${w}.json`)}function n$($){if(!Number.isInteger($)||$<=0)return!1;try{return TU.kill($,0),!0}catch(w){return w.code==="EPERM"}}function tF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&d1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function $q($){await i$.mkdir($,{recursive:!0})}async function rF($,w=Jw(),A){if(!tF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await $q(w);let J=Xf(w,$.id),U=`${J}.tmp.${TU.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await i$.writeFile(U,Y,{encoding:"utf8",mode:420}),await i$.rename(U,J),H("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await i$.unlink(U).catch(()=>{}),f}}async function _f($,w=Jw(),A){let J=Xf(w,$);try{await i$.unlink(J),H("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function wq($,w=Jw(),A){let J=Xf(w,$);try{let U=await i$.readFile(J,"utf8"),Y=JSON.parse(U);if(!tF(Y))return H("registry",`entry ${$} failed validation, removing`,A),await i$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return H("registry",`entry ${$} has invalid JSON, removing`,A),await i$.unlink(J).catch(()=>{}),null;throw U}}async function Gw($=Jw(),w){let A;try{A=await i$.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let J=[];for(let U of A){if(!U.endsWith(".json"))continue;let Y=U.slice(0,-5);if(!d1(Y))continue;let f=await wq(Y,$,w);if(f)J.push(f)}return J}async function GU($=Jw(),w){let A=await Gw($,w),J=0;for(let U of A){if(U.pid===void 0)continue;if(!n$(U.pid))H("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await _f(U.id,$,w).catch(()=>{}),J++}return J}function Df($,w={}){let A=w.dir??Jw(),J=w.debounceMs??100,U=w.pollMs??Math.max(J*2,250),Y=w.verbose;HU.mkdirSync(A,{recursive:!0});let f=null,W=!1,Z=null,B=!1,E=(h)=>{return JSON.stringify(h.map((q)=>({id:q.id,from:q.from,to:q.to,pid:q.pid,pathRewrites:q.pathRewrites,cleanUrls:q.cleanUrls,changeOrigin:q.changeOrigin})).sort((q,N)=>q.id.localeCompare(N.id)))},F=()=>{if(f=null,W)return;Gw(A,Y).then((h)=>{return Z=E(h),$(h)}).catch((h)=>{H("registry",`watcher onChange failed: ${h}`,Y)})},z=()=>{if(W)return;if(f)clearTimeout(f);f=setTimeout(F,J)},G=setInterval(()=>{if(W||B)return;B=!0,Gw(A,Y).then((h)=>{if(E(h)!==Z)z()}).catch((h)=>{H("registry",`watcher poll failed: ${h}`,Y)}).finally(()=>{B=!1})},U),T=HU.watch(A,{persistent:!0},(h,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;z()});return T.on("error",(h)=>{H("registry",`watcher error: ${h}`,Y)}),z(),{close:()=>{if(W=!0,f)clearTimeout(f);clearInterval(G),T.close()}}}var e7;var g1=X$(()=>{Y$();e7=/^[a-zA-Z0-9._-]+$/});import{spawn as Aq}from"node:child_process";import*as hw from"node:fs/promises";import{homedir as Jq}from"node:os";import*as l1 from"node:path";import*as c$ from"node:process";function m0(){return l1.join(Jq(),".stacks","rpx")}function sF($=m0()){return l1.join($,"daemon.pid")}async function aF($=m0()){try{let w=await hw.readFile(sF($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function Uq($=m0()){await hw.unlink(sF($)).catch(()=>{})}function Yq(){let $=c$.execPath,w=l1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&c$.argv[1])return[$,c$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function oF($={}){let w=$.rpxDir??m0(),A=$.verbose??!1;await Uw({rpxDir:w,verbose:A}).catch((E)=>{H("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let J=await aF(w);if(J!==null&&n$(J))return H("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)H("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await Uq(w);await hw.mkdir(w,{recursive:!0});let U=$.spawnCommand??Yq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");H("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=Aq(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??c$.cwd(),env:$.spawnEnv?{...c$.env,...$.spawnEnv}:c$.env});Y.unref();let f=null;Y.once("error",(E)=>{f=E});let W=$.startupTimeoutMs??5000,Z=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(f)throw f;let E=await aF(w);if(E!==null&&n$(E))return H("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((F)=>setTimeout(F,Z))}if(f)throw f;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var kf=X$(()=>{r0();jU();zU();g1();G1();Y$()});import*as Yw from"node:fs/promises";import{homedir as fq}from"node:os";import*as Qf from"node:path";function $j(){return Qf.join(fq(),".stacks","rpx")}function xf($=$j()){return Qf.join($,Zq)}async function qU($=$j()){try{let w=await Yw.readFile(xf($),"utf8"),A=JSON.parse(w);if(A.version!==hU||!Array.isArray(A.resolvers))return null;return{version:hU,resolvers:A.resolvers.filter((J)=>typeof J==="string"),domains:Array.isArray(A.domains)?A.domains.filter((J)=>typeof J==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function wj($,w){await Yw.mkdir($,{recursive:!0}),await Yw.writeFile(xf($),`${JSON.stringify(w,null,2)}
|
|
200
|
-
`,"utf8")}async function
|
|
203
|
+
`,j=D$(XJ.tmpdir(),"rpx-trust.ps1");if(await G$.writeFile(j,E),I1(`powershell -ExecutionPolicy Bypass -File "${j}"`),$.verbose)q.success("Successfully added certificate to Windows trust store");B=!0}catch(E){if($.verbose)q.warn(`Could not trust certificate: ${E}`)}else try{await JU(W,X.certificate,A),B=!0}catch(E){if($.verbose)q.warn(`Could not add certificate to trust store: ${E}`)}if(Ww={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)q.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),q.warn("This will bypass the warning and you should only need to do it once")}function j6(){Ww=null}async function g0($){if(!$)return null;if(Ww)return Ww;let w=$A($);try{let[A,Y,f]=await Promise.all([G$.access(w.keyPath).then(()=>!0).catch(()=>!1),G$.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?G$.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!Y)return z("ssl",`Certificate files don't exist: key=${A}, cert=${Y}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let X="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,W=X?U!==!1:!0;z("ssl",`Trust check: hasFlag=${X}, flagValue=${U}, shouldCheckTrust=${W}`,$.verbose);let J=w.basePath||D$(Df(),".stacks","ssl"),B=nT(J);if(!(W?await dT(B.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[j,T,F]=await Promise.all([G$.readFile(w.keyPath,"utf8"),G$.readFile(w.certPath,"utf8"),f&&w.caCertPath?G$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(yw($))try{let{X509Certificate:H}=await import("node:crypto"),G=new H(T).subjectAltName||"",R=$.proxies.map((M)=>M.to).filter((M)=>!G.includes(`DNS:${M}`));if(R.length>0)return z("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,$.verbose),null}catch(H){z("ssl",`Could not verify cert SANs: ${H}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),Ww={key:j,cert:T,ca:F},Ww}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function $A($,w){let A=Of($);z("ssl",`Primary domain: ${A}`,w);let Y=vT($),f=D$(Df(),".stacks","ssl");if(typeof $.https==="object"){let X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:f,U={domain:A,hostCertCN:A,basePath:X,caCertPath:$.https.caCertPath||Y.caCertPath,certPath:$.https.certPath||Y.certPath,keyPath:$.https.keyPath||Y.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(uT($)).map((W)=>({type:2,value:W}))};if(sU($.https.rootCA))U.rootCA=$.https.rootCA;return U}return{domain:A,hostCertCN:A,basePath:f,...Y,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(uT($)).map((X)=>({type:2,value:X}))}}async function mT($,w){let A=vT({to:$,verbose:w}),Y=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(Y.map((f)=>eU(f,w)))}async function dT($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Jw.platform==="darwin"){if(w?.serverName)return YJ($,w.serverName,{verbose:w.verbose});return _f($,{verbose:w.verbose})}else if(Jw.platform==="win32")try{let Y=I1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!Y)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(I1(f).toString().includes(Y))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(Jw.platform==="linux")try{let Y=I1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of f)try{if(I1(`find ${X} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${Y}"`).toString().includes(Y))return z("ssl",`Certificate fingerprint found in ${X}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${Jw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var Ww=null,W6="rpx-root-ca.crt",B6="rpx-root-ca.key";var kf=K$(()=>{WU();$w();TU();fJ();X$();fJ();FU()});import*as W0 from"node:path";function wA($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function F6($){let w=W0.extname($).toLowerCase();return T6[w]??"application/octet-stream"}function z6($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=W0.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function h6($,w){let A=z6($);if(A===null)return null;let Y=W0.posix.extname(A);if(w.cleanUrls&&Y===".html"){let f=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:W0.join(w.dir,A),redirectTo:f||"/"}}if(A===""||$.endsWith("/"))return{filePath:W0.join(w.dir,A,"index.html")};if(Y!=="")return{filePath:W0.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:W0.join(w.dir,`${A}.html`)};return{filePath:W0.join(w.dir,A,"index.html")}}async function lT($,w){let A=h6($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let Y=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",f=Bun.file(A.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":F6(A.filePath),"Cache-Control":Y}});if(w.spa){let X=W0.join(w.dir,"index.html"),U=Bun.file(X);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 T6;var AA=K$(()=>{T6={".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 G6($){return($.headers.get("host")||"").split(":")[0]}function gT($,w,A){let Y=new URL($.url),f=w.sourceHost??"",X=Y.pathname,U=oU(Y.pathname,w.pathRewrites);if(U)f=U.targetHost,X=U.targetPath,z("request",`Path rewrite: ${Y.pathname} → ${f}${X}`,A);return{targetHost:f,targetPath:X,search:Y.search}}function YA($,w){return async(A,Y)=>{let f=new URL(A.url),X=G6(A),U=$(X);if(!U)return z("request",`No route found for host: ${X}`,w),new Response(`No proxy configured for ${X}`,{status:404});if(U.static)return lT(f.pathname,U.static);if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!Y||!U.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:j,targetPath:T,search:F}=gT(A,U,w),H=`ws://${j}${T}${F}`,h={};for(let[R,M]of A.headers)if(!H6.has(R.toLowerCase())&&R.toLowerCase()!=="host")h[R]=M;h.host=j,h["x-forwarded-for"]="127.0.0.1",h["x-forwarded-proto"]="https",h["x-forwarded-host"]=X;let G={targetUrl:H,forwardHeaders:h};if(Y.upgrade(A,{data:G})){z("ws",`upgraded ${X}${T} → ${H}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!U.sourceHost)return new Response(`No upstream configured for ${X}`,{status:502});let{targetHost:W,targetPath:J,search:B}=gT(A,U,w),E=`http://${W}${J}${B}`;try{let j=new Headers(A.headers);if(j.set("host",W),U.changeOrigin)j.set("origin",`http://${U.sourceHost}`);j.set("x-forwarded-for","127.0.0.1"),j.set("x-forwarded-proto","https"),j.set("x-forwarded-host",X);let T=await fetch(E,{method:A.method,headers:j,body:A.body,redirect:"manual"});if(U.cleanUrls&&f.pathname.endsWith(".html")){let H=f.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H}})}let F=new Headers(T.headers);return new Response(T.body,{status:T.status,statusText:T.statusText,headers:F})}catch(j){return z("request",`Proxy error for ${X}: ${j}`,w),new Response(`Proxy Error: ${j}`,{status:502})}}}function fA($){let w=new WeakMap;return{open(A){let{targetUrl:Y,forwardHeaders:f}=A.data,X;try{X=new WebSocket(Y,{headers:f})}catch(W){z("ws",`failed to open upstream ${Y}: ${W}`,$),A.close(1011,"upstream connect failed");return}X.binaryType="arraybuffer";let U={upstream:X,upstreamOpen:!1,pending:[]};w.set(A,U),X.addEventListener("open",()=>{U.upstreamOpen=!0;for(let W of U.pending)X.send(W);U.pending=[]}),X.addEventListener("message",(W)=>{A.send(W.data)}),X.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),X.addEventListener("error",()=>{z("ws",`upstream error for ${Y}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,Y){let f=w.get(A);if(!f)return;let X=typeof Y==="string"?Y:new Uint8Array(Y);if(f.upstreamOpen)f.upstream.send(X);else f.pending.push(X)},close(A,Y,f){let X=w.get(A);if(!X)return;w.delete(A);try{X.upstream.close(Y||1000,f||"")}catch{}}}}var H6;var Zf=K$(()=>{AA();X$();H6=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function xf($){return $.startsWith("*.")}function R6($,w){if(!xf(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function XA($,w){let A=$.get(w);if(A!==void 0)return A;let Y,f=-1;for(let[X,U]of $){if(!xf(X))continue;if(R6(w,X)){let W=X.length-1;if(W>f)f=W,Y=U}}return Y}import*as UA from"node:fs/promises";import*as UJ from"node:path";function q6($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function N6($,w,A,Y){try{let[f,X]=await Promise.all([UA.readFile(w,"utf8"),UA.readFile(A,"utf8")]);return{serverName:$,cert:f,key:X}}catch(f){return z("sni",`skipping ${$}: ${f.message}`,Y),null}}async function JJ($,w){let A=new Map;if($.certsDir){let f=[];try{f=await UA.readdir($.certsDir)}catch(X){z("sni",`certsDir read failed (${$.certsDir}): ${X.message}`,w)}for(let X of f){let U=q6(X);if(!U)continue;let W=X.slice(0,-4);A.set(U,{certPath:UJ.join($.certsDir,X),keyPath:UJ.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[f,X]of Object.entries($.domains))A.set(f,X);let Y=[];for(let[f,X]of A){let U=await N6(f,X.certPath,X.keyPath,w);if(U)Y.push(U)}return Y}var WJ=K$(()=>{X$()});import*as Bw from"node:fs/promises";import*as BJ from"node:path";function M6($,w){if(!w||w.length===0)return!1;return w.some((A)=>{let Y=A.startsWith(".")?A.slice(1):A;return $===Y||$.endsWith(`.${Y}`)})}function I6($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class Pf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??lY,this.issuer=$.issuer??l8,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??y6;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!I6($))return!1;if(M6($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return z("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;let w=this.inFlight.get($);if(w)return w;let A=this.negativeCache.get($);if(A!==void 0&&Date.now()<A)return z("on-demand",`${$} negatively cached for ${A-Date.now()}ms`,this.verbose),!1;let Y=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,Y),Y}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return z("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),!1;try{z("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let A={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,A),this.negativeCache.delete($),z("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.negativeCache.set($,Date.now()+this.negativeCacheMs),z("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}async loadFromDisk($){let{certPath:w,keyPath:A}=this.pathsFor($);try{let[Y,f]=await Promise.all([Bw.readFile(w,"utf8"),Bw.readFile(A,"utf8")]),X={serverName:$,cert:Y,key:f};return this.certs.set($,X),z("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:BJ.join(this.certsDir,`${$}.crt`),keyPath:BJ.join(this.certsDir,`${$}.key`)}}async persist($,w,A){await Bw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:Y,keyPath:f}=this.pathsFor($);await Promise.all([Bw.writeFile(Y,w,"utf8"),Bw.writeFile(f,A,{encoding:"utf8",mode:384})])}}var y6=60000;var EJ=K$(()=>{WU();X$()});import*as bf from"node:fs";import*as u$ from"node:fs/promises";import{homedir as C6}from"node:os";import*as jJ from"node:path";import*as cf from"node:process";function Ew(){return jJ.join(C6(),".stacks","rpx","registry.d")}function JA($){return typeof $==="string"&&$.length>0&&$.length<=128&&S6.test($)}function TJ($,w){if(!JA(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return jJ.join($,`${w}.json`)}function l$($){if(!Number.isInteger($)||$<=0)return!1;try{return cf.kill($,0),!0}catch(w){return w.code==="EPERM"}}function tT($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string";return typeof w.id==="string"&&JA(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function L6($){await u$.mkdir($,{recursive:!0})}async function pT($,w=Ew(),A){if(!tT($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await L6(w);let Y=TJ(w,$.id),f=`${Y}.tmp.${cf.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await u$.writeFile(f,X,{encoding:"utf8",mode:420}),await u$.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await u$.unlink(f).catch(()=>{}),U}}async function FJ($,w=Ew(),A){let Y=TJ(w,$);try{await u$.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function O6($,w=Ew(),A){let Y=TJ(w,$);try{let f=await u$.readFile(Y,"utf8"),X=JSON.parse(f);if(!tT(X))return z("registry",`entry ${$} failed validation, removing`,A),await u$.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await u$.unlink(Y).catch(()=>{}),null;throw f}}async function Mw($=Ew(),w){let A;try{A=await u$.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!JA(X))continue;let U=await O6(X,$,w);if(U)Y.push(U)}return Y}async function uf($=Ew(),w){let A=await Mw($,w),Y=0;for(let f of A){if(f.pid===void 0)continue;if(!l$(f.pid))z("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,w),await FJ(f.id,$,w).catch(()=>{}),Y++}return Y}function zJ($,w={}){let A=w.dir??Ew(),Y=w.debounceMs??100,f=w.pollMs??Math.max(Y*2,250),X=w.verbose;bf.mkdirSync(A,{recursive:!0});let U=null,W=!1,J=null,B=!1,E=(G)=>{return JSON.stringify(G.map((K)=>({id:K.id,from:K.from,to:K.to,pid:K.pid,pathRewrites:K.pathRewrites,cleanUrls:K.cleanUrls,changeOrigin:K.changeOrigin,static:K.static})).sort((K,R)=>K.id.localeCompare(R.id)))},j=()=>{if(U=null,W)return;Mw(A,X).then((G)=>{return J=E(G),$(G)}).catch((G)=>{z("registry",`watcher onChange failed: ${G}`,X)})},T=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(j,Y)},H=setInterval(()=>{if(W||B)return;B=!0,Mw(A,X).then((G)=>{if(E(G)!==J)T()}).catch((G)=>{z("registry",`watcher poll failed: ${G}`,X)}).finally(()=>{B=!1})},f),h=bf.watch(A,{persistent:!0},(G,K)=>{if(K&&/\.tmp\.\d+\.\d+$/.test(K))return;T()});return h.on("error",(G)=>{z("registry",`watcher error: ${G}`,X)}),T(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(H),h.close()}}}var S6;var WA=K$(()=>{X$();S6=/^[a-zA-Z0-9._-]+$/});import{spawn as V6}from"node:child_process";import*as Iw from"node:fs/promises";import{homedir as Q6}from"node:os";import*as BA from"node:path";import*as n$ from"node:process";function t0(){return BA.join(Q6(),".stacks","rpx")}function aT($=t0()){return BA.join($,"daemon.pid")}async function rT($=t0()){try{let w=await Iw.readFile(aT($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function _6($=t0()){await Iw.unlink(aT($)).catch(()=>{})}function D6(){let $=n$.execPath,w=BA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&n$.argv[1])return[$,n$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function sT($={}){let w=$.rpxDir??t0(),A=$.verbose??!1;await jw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await rT(w);if(Y!==null&&l$(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await _6(w);await Iw.mkdir(w,{recursive:!0});let f=$.spawnCommand??D6();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=V6(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??n$.cwd(),env:$.spawnEnv?{...n$.env,...$.spawnEnv}:n$.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await rT(w);if(E!==null&&l$(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var hJ=K$(()=>{$w();kf();Zf();WJ();EJ();AA();WA();S1();X$()});import*as Tw from"node:fs/promises";import{homedir as k6}from"node:os";import*as HJ from"node:path";function eT(){return HJ.join(k6(),".stacks","rpx")}function GJ($=eT()){return HJ.join($,Z6)}async function vf($=eT()){try{let w=await Tw.readFile(GJ($),"utf8"),A=JSON.parse(w);if(A.version!==nf||!Array.isArray(A.resolvers))return null;return{version:nf,resolvers:A.resolvers.filter((Y)=>typeof Y==="string"),domains:Array.isArray(A.domains)?A.domains.filter((Y)=>typeof Y==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function $F($,w){await Tw.mkdir($,{recursive:!0}),await Tw.writeFile(GJ($),`${JSON.stringify(w,null,2)}
|
|
204
|
+
`,"utf8")}async function KJ($){await Tw.rm(GJ($),{force:!0})}function wF($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;return w}function x6($){let w=wF($);if(!w)return null;let A=w.split(".");if(A.length<2)return null;return A.slice(-2).join(".")}function RJ($){let w=new Set;for(let A of $){let Y=x6(A);if(Y)w.add(Y)}return Array.from(w).sort()}function qJ($){let w=new Set;for(let A of $){let Y=wF(A);if(Y)w.add(Y)}return Array.from(w).sort()}var nf=1,Z6="dns-state.json",oT;var AF=K$(()=>{oT=["com","test","dev","app","page","local","localhost","example","invalid"]});var gf={};nJ(gf,{tearDownDevelopmentDns:()=>Cw,syncDevelopmentDnsFromRegistry:()=>EA,stopDnsServer:()=>NJ,startDnsServer:()=>WF,setupResolver:()=>g6,setupDevelopmentDns:()=>CJ,resolverFilePath:()=>L1,removeResolver:()=>p6,removeLegacyTldResolvers:()=>IJ,reconcileStaleDevelopmentDns:()=>jw,isDnsServerRunning:()=>n6,contentLooksLikeRpxResolver:()=>BF,RPX_RESOLVER_MARKER:()=>XF,DNS_PORT:()=>lf});import P6 from"node:dgram";import*as YF from"node:fs/promises";import*as fF from"node:path";import*as p0 from"node:process";function i6($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function JF($,w){let A=[],Y=w;while(!0){let f=$[Y];if(f===0){Y++;break}if((f&192)===192){let X=$.readUInt16BE(Y)&16383,{name:U}=JF($,X);A.push(U),Y+=2;break}Y++,A.push($.subarray(Y,Y+f).toString("ascii")),Y+=f}return{name:A.join("."),newOffset:Y}}function b6($,w){let{name:A,newOffset:Y}=JF($,w),f=$.readUInt16BE(Y),X=$.readUInt16BE(Y+2);return{question:{name:A,type:f,class:X},newOffset:Y+4}}function df($){let w=$.split("."),A=[];for(let Y of w)A.push(Buffer.from([Y.length])),A.push(Buffer.from(Y,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function c6($,w,A){let Y=[],f=Buffer.alloc(12);f.writeUInt16BE($,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),Y.push(f),Y.push(df(w.name));let X=Buffer.alloc(4);X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),Y.push(X),Y.push(df(w.name));let U=Buffer.alloc(10);if(U.writeUInt16BE(w.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),w.type===1){U.writeUInt16BE(4,8),Y.push(U);let W=A.split(".").map((J)=>Number.parseInt(J,10));Y.push(Buffer.from(W))}else if(w.type===28)U.writeUInt16BE(16,8),Y.push(U),Y.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,df(w.name),X]);return Buffer.concat(Y)}function u6($,w){let A=[],Y=Buffer.alloc(12);Y.writeUInt16BE($,0),Y.writeUInt16BE(33155,2),Y.writeUInt16BE(1,4),Y.writeUInt16BE(0,6),Y.writeUInt16BE(0,8),Y.writeUInt16BE(0,10),A.push(Y),A.push(df(w.name));let f=Buffer.alloc(4);return f.writeUInt16BE(w.type,0),f.writeUInt16BE(w.class,2),A.push(f),Buffer.concat(A)}async function WF($,w){if(p0.platform!=="darwin")return!1;let A=qJ($);if(A.length===0)return!1;if(g$){for(let Y of A)mf.add(Y);return z("dns","DNS server already running — merged domains",w),!0}return mf=new Set(A),new Promise((Y)=>{g$=P6.createSocket("udp4"),g$.on("error",(f)=>{z("dns",`DNS server error: ${f.message}`,w),g$?.close(),g$=null,Y(!1)}),g$.on("message",(f,X)=>{try{let U=i6(f),{question:W}=b6(f,12);z("dns",`Query for ${W.name} type ${W.type} from ${X.address}`,w);let J=W.name.toLowerCase(),B=!1;for(let j of mf)if(J===j||J.endsWith(`.${j}`)){B=!0;break}let E;if(B&&(W.type===1||W.type===28))E=c6(U.id,W,"127.0.0.1"),z("dns",`Responding with localhost for ${W.name}`,w);else E=u6(U.id,W),z("dns",`NXDOMAIN for ${W.name}`,w);g$?.send(E,X.port,X.address)}catch(U){z("dns",`Error processing DNS query: ${U}`,w)}}),g$.on("listening",()=>{let f=g$?.address();z("dns",`DNS server listening on ${f?.address}:${f?.port}`,w),Y(!0)});try{g$.bind(lf,"127.0.0.1")}catch(f){z("dns",`Failed to bind DNS server: ${f}`,w),Y(!1)}})}function NJ($){if(g$)z("dns","Stopping DNS server",$),g$.close(),g$=null,mf=new Set}function n6(){return g$!==null}function v6(){return`${XF}
|
|
201
205
|
nameserver 127.0.0.1
|
|
202
|
-
port ${
|
|
203
|
-
`}function
|
|
206
|
+
port ${lf}
|
|
207
|
+
`}function L1($){return fF.join(UF,$)}function BF($){return $.includes("127.0.0.1")&&$.includes(String(lf))}async function m6($){try{return await YF.readFile(L1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function yJ($){if(p0.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (X$(),N1));if(!A()){z("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),z("dns","DNS cache flushed",$)}catch(Y){z("dns",`Could not flush DNS cache: ${Y}`,$)}}async function d6($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (X$(),N1)),Y=v6().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${UF} && printf "%b" "${Y}" > ${L1($)}'`;A(f),z("dns",`Created ${L1($)}`,w)}async function l6($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (X$(),N1));A(`rm -f ${L1($)}`),z("dns",`Removed ${L1($)}`,w)}async function g6($,w){return CJ({domains:w??[],verbose:$})}async function t6($,w){if(p0.platform!=="darwin")return!0;let{getSudoPassword:A}=await Promise.resolve().then(() => (X$(),N1));if(!A())return z("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let Y of $)await d6(Y,w);return await yJ(w),!0}catch(Y){return z("dns",`Failed to create resolver file: ${Y}`,w),!1}}async function MJ($,w){if(p0.platform!=="darwin")return;let{getSudoPassword:A}=await Promise.resolve().then(() => (X$(),N1));if(!A())return;try{for(let Y of $)await l6(Y,w);await yJ(w)}catch(Y){z("dns",`Failed to remove resolver files: ${Y}`,w)}}async function IJ($){if(p0.platform!=="darwin")return[];let w=[];for(let A of oT){let Y=await m6(A);if(Y&&BF(Y))await MJ([A],$),w.push(A)}return w}async function CJ($){let w=$.rpxDir??t0(),A=qJ($.domains);if(A.length===0)return!1;let Y=RJ(A);if(!await WF(A,$.verbose))return!1;if(!await t6(Y,$.verbose))return!1;let U={version:nf,resolvers:Y,domains:A,ownerPid:$.ownerPid??p0.pid,updatedAt:new Date().toISOString()};return await $F(w,U),!0}async function EA($,w={}){let A=$.map((J)=>J.to).filter(Boolean),Y=w.rpxDir??t0(),f=RJ(A),W=((await vf(Y))?.resolvers??[]).filter((J)=>!f.includes(J));if(W.length>0)await MJ(W,w.verbose);if(f.length===0){NJ(w.verbose),await KJ(Y);return}await CJ({domains:A,rpxDir:Y,verbose:w.verbose,ownerPid:w.ownerPid??p0.pid})}async function Cw($={}){let w=$.rpxDir??t0();NJ($.verbose);let Y=(await vf(w))?.resolvers??[];await MJ(Y,$.verbose),await IJ($.verbose),await KJ(w)}async function p6($){await Cw({verbose:$})}async function jw($={}){let w=$.rpxDir??t0(),A=await vf(w),Y=A?.ownerPid!=null&&l$(A.ownerPid);if(A&&!Y){z("dns",`reconcile: owner pid ${A.ownerPid} is gone — tearing down DNS`,$.verbose),await Cw($);return}let f=await IJ($.verbose);if(f.length>0)z("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,$.verbose);await yJ($.verbose)}var lf=15353,XF="# managed-by: rpx",UF="/etc/resolver",g$=null,mf;var S1=K$(()=>{hJ();AF();WA();X$();mf=new Set});import{dirname as G7,join as K7}from"path";import*as m$ from"process";import{fileURLToPath as R7}from"url";import{existsSync as uF}from"node:fs";import fX from"node:fs/promises";import vJ from"node:os";import XX from"node:path";import hw from"node:process";import{EventEmitter as nF}from"node:events";import a0 from"node:process";import mJ from"node:process";import BX from"node:process";import qA from"node:process";import D1 from"node:process";import gJ from"node:tty";import Oz,{stdin as c7,stdout as u7}from"node:process";import pJ,{stdin as _z,stdout as Dz}from"node:process";import kz from"node:readline";class aJ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=vJ.homedir(),w=XX.join($,".config","clapp");this.configPath=XX.join(w,"telemetry.json")}async isEnabled(){if(hw.env.DO_NOT_TRACK==="1"||hw.env.DO_NOT_TRACK==="true")return!1;if(hw.env.NO_TELEMETRY==="1"||hw.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let Y={event:$,...w,timestamp:Date.now(),platform:vJ.platform(),nodeVersion:hw.version};if(this.events.push(Y),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:hw.env.DO_NOT_TRACK==="1"||hw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(uF(this.configPath)){let $=await fX.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=XX.dirname(this.configPath);await fX.mkdir(w,{recursive:!0}),await fX.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var L7=new aJ;function vF($,w={}){let A={_:[]},Y=w.alias||{},f=new Set(w.boolean||[]),X={};for(let W of Object.keys(Y))for(let J of Y[W])X[J]=W;for(let W of f)if(Y[W])for(let J of Y[W])f.add(J);function U(W,J){let B=X[W]||W;if(A[B]=J,Y[B])for(let E of Y[B])A[E]=J;if(X[W]&&Y[X[W]])for(let E of Y[X[W]])A[E]=J;A[W]=J}for(let W=0;W<$.length;W++){let J=$[W];if(J==="--"){A._.push(...$.slice(W+1));break}if(J.startsWith("--")){let B=J.indexOf("=");if(B!==-1){let E=J.slice(2,B),j=J.slice(B+1);U(E,j)}else{let E=J.slice(2);if(E.startsWith("no-")){let T=E.slice(3);U(T,!1);continue}let j=X[E]||E;if(f.has(j)||f.has(E))U(E,!0);else{let T=$[W+1];if(T!==void 0&&!T.startsWith("-"))U(E,T),W++;else U(E,!0)}}}else if(J.startsWith("-")&&J.length>1){let B=J.slice(1);for(let E=0;E<B.length;E++){let j=B[E],T=X[j]||j;if(E===B.length-1&&!f.has(T)&&!f.has(j)){let F=$[W+1];if(F!==void 0&&!F.startsWith("-"))U(j,F),W++;else U(j,!0)}else U(j,!0)}}else A._.push(J)}return A}function WX($){return $.replace(/[<[].+/,"").trim()}function mF($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,Y=[],f=(W)=>{let J=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),J=!0;return{required:W[0].startsWith("<"),value:B,variadic:J}},X;while(X=w.exec($))Y.push(f(X));let U;while(U=A.exec($))Y.push(f(U));return Y}function dF($){let w={alias:{},boolean:[]};for(let[A,Y]of $.entries()){if(Y.names.length>1)w.alias[Y.names[0]]=Y.names.slice(1);if(Y.isBoolean)if(Y.negated){if(!$.some((X,U)=>{return U!==A&&X.names.some((W)=>Y.names.includes(W))&&typeof X.required==="boolean"}))w.boolean.push(Y.names[0])}else w.boolean.push(Y.names[0])}return w}function dJ($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function UX($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function lF($){return $.replace(/([a-z])-([a-z])/g,(w,A,Y)=>{return A+Y.toUpperCase()})}function gF($,w,A){let Y=0,f=w.length,X=$,U;for(;Y<f;++Y)U=X[w[Y]],X=X[w[Y]]=Y===f-1?A:U!=null?U:!!~w[Y+1].indexOf(".")||!(+w[Y+1]>-1)?{}:[]}function tF($,w){for(let A of Object.keys(w)){let Y=w[A];if(Y.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof Y.transformFunction==="function")$[A]=$[A].map(Y.transformFunction)}}}function pF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function sJ($){return $.split(".").map((w,A)=>{return A===0?lF(w):w}).join(".")}class RA extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
204
208
|
|
|
205
209
|
Stack trace:
|
|
206
|
-
${this.stack}`;return this.message}}function
|
|
207
|
-
`);let
|
|
210
|
+
${this.stack}`;return this.message}}function rF(){let{env:$}=mJ,{TERM:w,TERM_PROGRAM:A}=$;if(mJ.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||A==="Terminus-Sublime"||A==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var MA="\x1B",U$=`${MA}[`;var I0={to($,w){if(!w)return`${U$}${$+1}G`;return`${U$}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${U$}${-$}D`;else if($>0)A+=`${U$}${$}C`;if(w<0)A+=`${U$}${-w}A`;else if(w>0)A+=`${U$}${w}B`;return A},up:($=1)=>`${U$}${$}A`,down:($=1)=>`${U$}${$}B`,forward:($=1)=>`${U$}${$}C`,backward:($=1)=>`${U$}${$}D`,nextLine:($=1)=>`${U$}E`.repeat($),prevLine:($=1)=>`${U$}F`.repeat($),left:`${U$}G`,hide:`${U$}?25l`,show:`${U$}?25h`,save:`${MA}7`,restore:`${MA}8`};var JX={screen:`${U$}2J`,up:($=1)=>`${U$}1J`.repeat($),down:($=1)=>`${U$}J`.repeat($),line:`${U$}2K`,lineEnd:`${U$}K`,lineStart:`${U$}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?I0.up():"");if($)w+=I0.left;return w}},_7={screen:`${MA}c`};function aF($,w){let A=[];for(let Y=0;Y<=w.length;Y++)A[Y]=[Y];for(let Y=0;Y<=$.length;Y++)A[0][Y]=Y;for(let Y=1;Y<=w.length;Y++)for(let f=1;f<=$.length;f++)if(w.charAt(Y-1)===$.charAt(f-1))A[Y][f]=A[Y-1][f-1];else A[Y][f]=Math.min(A[Y-1][f-1]+1,A[Y][f-1]+1,A[Y-1][f]+1);return A[w.length][$.length]}function oJ($,w,A=2,Y=3){return w.map((f)=>({cmd:f,distance:aF($,f)})).filter(({distance:f})=>f<=A).sort((f,X)=>f.distance-X.distance).slice(0,Y).map(({cmd:f})=>f)}class eJ{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,A){if(this.rawName=$,this.description=w,this.config=Object.assign({},A),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=WX($).split(",").map((Y)=>{let f=Y.trim().replace(/^-{1,2}/,"");if(f.startsWith("no-"))this.negated=!0,f=f.replace(/^no-/,"");return sJ(f)}).sort((Y,f)=>Y.length>f.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var k7=BX.argv,sF=`${BX.platform}-${BX.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,lJ=qA.argv,oF=`${qA.platform}-${qA.arch} node-${qA.version}`;class EX{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,A,Y){this.rawName=$,this.description=w,this.config=A,this.cli=Y,this.options=[],this.aliasNames=[],this.name=WX($);let f=WX($),X=f.indexOf(":");if(X>0)this.namespace=f.substring(0,X),this.name=f.substring(X+1);if(this.args=mF($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!A)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,A){let Y=new eJ($,w,A);return this.options.push(Y),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof jX}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:A,options:Y,helpCallback:f}=this.cli.globalCommand,X=[{body:`${$}${A?`/${A}`:""}`}];if(X.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let J=dJ(w.map((F)=>F.rawName)),B=new Map,E=[];for(let F of w)if(F.namespace){if(!B.has(F.namespace))B.set(F.namespace,[]);B.get(F.namespace).push(F)}else E.push(F);let j="";if(E.length>0)j+=E.map((F)=>{return` ${UX(F.rawName,J.length)} ${F.description}`}).join(`
|
|
211
|
+
`);let T=Array.from(B.keys()).sort();for(let F of T){let H=B.get(F);if(j.length>0)j+=`
|
|
208
212
|
|
|
209
|
-
`;
|
|
210
|
-
`,
|
|
211
|
-
`)}
|
|
212
|
-
`)})}let W=this.isGlobalCommand?
|
|
213
|
-
`)})}if(this.examples.length>0)
|
|
214
|
-
`)});if(
|
|
215
|
-
${
|
|
213
|
+
`;j+=` ${F}:
|
|
214
|
+
`,j+=H.map((h)=>{return` ${UX(h.rawName,J.length-2)} ${h.description}`}).join(`
|
|
215
|
+
`)}X.push({title:"Commands",body:j}),X.push({title:"For more info, run any command with the `--help` flag",body:w.map((F)=>` $ ${$}${F.displayName===""?"":` ${F.displayName}`} --help`).join(`
|
|
216
|
+
`)})}let W=this.isGlobalCommand?Y:[...this.options,...Y||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((J)=>J.name!=="version");if(W.length>0){let J=dJ(W.map((B)=>B.rawName));X.push({title:"Options",body:W.map((B)=>{return` ${UX(B.rawName,J.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
|
|
217
|
+
`)})}if(this.examples.length>0)X.push({title:"Examples",body:this.examples.map((J)=>{if(typeof J==="function")return J($);return J}).join(`
|
|
218
|
+
`)});if(f)X=f(X)||X;console.log(X.map((J)=>{return J.title?`${J.title}:
|
|
219
|
+
${J.body}`:J.body}).join(`
|
|
216
220
|
|
|
217
|
-
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?
|
|
221
|
+
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?sF:oF}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((f)=>f.required).slice(this.cli.args.length),Y=A.map((f)=>`<${f.value}>`).join(" ");throw new RA(`Missing required argument${A.length>1?"s":""}: ${Y}
|
|
218
222
|
|
|
219
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let A of Object.keys($))if(A!=="--"&&!this.hasOption(A)&&!w.hasOption(A)){let
|
|
223
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let A of Object.keys($))if(A!=="--"&&!this.hasOption(A)&&!w.hasOption(A)){let f=[...w.options,...this.options].flatMap((J)=>J.names),X=A.length>1?`--${A}`:`-${A}`,U=oJ(A,f),W=`Unknown option \`${X}\``;if(U.length>0)W+=`
|
|
220
224
|
|
|
221
|
-
Did you mean one of these?`,
|
|
225
|
+
Did you mean one of these?`,U.forEach((J)=>{let B=J.length>1?`--${J}`:`-${J}`;W+=`
|
|
222
226
|
• ${B}`});throw W+=`
|
|
223
227
|
|
|
224
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
228
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new RA(W)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let Y of A){let f=$[Y.name.split(".")[0]];if(Y.required){let X=A.some((U)=>U.negated&&U.names.includes(Y.name));if(f===!0||f===!1&&!X)throw new RA(`Option \`${Y.rawName}\` requires a value.
|
|
225
229
|
|
|
226
|
-
Example: ${this.cli.name} ${this.rawName} ${
|
|
230
|
+
Example: ${this.cli.name} ${this.rawName} ${Y.rawName} <value>`)}}}}class jX extends EX{constructor($){super("@@global@@","",{},$)}}var eF=EX,s0={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 Q1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function $z(){return!0}function wz(){let $={};$.supportsColor=$z();function w(Y,f=[]){let X=Y===""?[]:[...f,Y],U=function(J){if(!$.supportsColor)return J;let B="",E="";for(let j of X)if(j in Q1&&Q1[j]in s0){let T=Q1[j];B+=s0[T][0],E=s0[T][1]+E}else if(j in s0)B+=s0[j][0],E=s0[j][1]+E;return B+J+E},W=[...Object.keys(s0),...Object.keys(Q1)];for(let J of W)if(!(J in U))Object.defineProperty(U,J,{get(){return w(J,X)}});return U}let A=[...Object.keys(s0),...Object.keys(Q1)];for(let Y of A)if(!(Y in $))Object.defineProperty($,Y,{get(){return w(Y)}});return $}var _1=wz();class TX extends nF{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new jX(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(A)=>{if(console.log(`
|
|
227
231
|
|
|
228
|
-
Received ${A}, cleaning up...`),$)try{await $()}catch(
|
|
232
|
+
Received ${A}, cleaning up...`),$)try{await $()}catch(Y){console.error("Error during cleanup:",Y)}a0.exit(0)};return a0.on("SIGINT",()=>w("SIGINT")),a0.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,A){if(!A)A={};let Y=new eF($,w||"",A,this);return Y.globalCommand=this.globalCommand,this.commands.push(Y),Y}option($,w,A){return this.globalCommand.option($,w,A),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},A,Y){if(this.args=$,this.options=w,A)this.matchedCommand=A;if(Y)this.matchedCommandName=Y;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(_1.red(`
|
|
229
233
|
✗ Command "${$}" not found.
|
|
230
|
-
`)),this.enableDidYouMean){let w=[];for(let
|
|
231
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
232
|
-
`),
|
|
233
|
-
`),
|
|
234
|
-
`),
|
|
235
|
-
`),
|
|
236
|
-
`)}class
|
|
237
|
-
`),
|
|
238
|
-
`).length-1;this.output.write(
|
|
239
|
-
`);this.output.write(
|
|
240
|
-
`).slice(A);this.output.write(
|
|
241
|
-
`)),this._prevFrame=$;return}this.output.write(
|
|
242
|
-
`)}finally{await
|
|
243
|
-
`),B.stdin.end();B.unref();let z=Zw($),j=Date.now()+15000;while(Date.now()<j){if(E)throw E;let G=await fw($);if(G!==null&&n$(G)){if(J)K.success(`rpx daemon elevated to root (pid=${G}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:z,done:Promise.resolve(),stop:async()=>{try{x.kill(G,"SIGTERM")}catch{}}}}if(F!==null&&F!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${F}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((T)=>setTimeout(T,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}async function jj($={}){let w=$.verbose??!1,A=$.rpxDir??U0(),J=$.registryDir??T0.join(A,"registry.d"),U=$.httpsPort??443,Y=$.httpPort??80,f=$.hostname??"0.0.0.0",W=$.gcIntervalMs??Mq,Z=U>0&&U<1024||Y>0&&Y<1024,B=typeof x.getuid==="function"&&x.getuid()===0;if(x.platform!=="win32"&&Z&&!B)return Sq(A,U,Y,w);let E=await Iq(A),F=new Map,z=(S)=>F.get(S);function j(S){let O$=new Map;for(let Ww of S)O$.set(Ww.to,yq(Ww));F=O$,H("daemon",`routing table now covers ${O$.size} host(s): ${Array.from(O$.keys()).join(", ")||"<empty>"}`,w)}await GU(J,w).catch((S)=>{H("daemon",`initial gc failed: ${S}`,w)});let G=await Gw(J,w);j(G),await Uw({rpxDir:A,verbose:w}).catch((S)=>{H("daemon",`DNS reconcile on start failed: ${S}`,w)}),await p1(G,{rpxDir:A,verbose:w,ownerPid:x.pid}).catch((S)=>{H("daemon",`DNS setup on start failed: ${S}`,w)});let T=await Lq($,J),h=Bun.serve({port:U,hostname:f,tls:{key:T.key,cert:T.cert,ca:T.ca,requestCert:!1,rejectUnauthorized:!1},fetch:m1(z,w),error(S){return H("daemon",`https server error: ${S}`,w),new Response(`Server Error: ${S.message}`,{status:500})}}),q=null;if(Y>0)q=Bun.serve({port:Y,hostname:f,fetch(S){let O$=new URL(S.url),Ww=(S.headers.get("host")??O$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${Ww}${O$.pathname}${O$.search}`}})}});if(w)K.success(`rpx daemon listening on https://${f}:${U}${q?` (http→https on :${Y})`:""}`),K.info(`pid file: ${E}`),K.info(`registry: ${J}`);let N=Df((S)=>{j(S),p1(S,{rpxDir:A,verbose:w,ownerPid:x.pid}).catch((O$)=>{H("daemon",`DNS sync on registry change failed: ${O$}`,w)})},{dir:J,verbose:w}),R=setInterval(()=>{GU(J,w).then((S)=>{if(S>0)H("daemon",`gc reaped ${S} stale entries`,w)}).catch((S)=>{H("daemon",`periodic gc failed: ${S}`,w)})},W);if(typeof R.unref==="function")R.unref();let y=!1,C,L=new Promise((S)=>{C=S});async function N0(){if(y)return L;if(y=!0,clearInterval(R),N.close(),h.stop(!1),q?.stop(!1),await qw({rpxDir:A,verbose:w}).catch((S)=>{H("daemon",`DNS teardown failed: ${S}`,w)}),await t1(A),w)K.info("rpx daemon stopped");return C(),L}let f0=(S)=>{H("daemon",`received ${S}, shutting down`,w),N0().catch(()=>{})};return x.once("SIGINT",f0),x.once("SIGTERM",f0),{stop:N0,done:L,httpsPort:typeof h.port==="number"?h.port:U,httpPort:q&&typeof q.port==="number"?q.port:Y,pidPath:E}}function Vq(){let $=x.execPath,w=T0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&x.argv[1])return[$,x.argv[1],"daemon:start"];return[$,"daemon:start"]}async function zj($={}){let w=$.rpxDir??U0(),A=$.verbose??!1;await Uw({rpxDir:w,verbose:A}).catch((E)=>{H("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let J=await fw(w);if(J!==null&&n$(J))return H("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)H("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await t1(w);await G0.mkdir(w,{recursive:!0});let U=$.spawnCommand??Vq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");H("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=Fj(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??x.cwd(),env:$.spawnEnv?{...x.env,...$.spawnEnv}:x.env});Y.unref();let f=null;Y.once("error",(E)=>{f=E});let W=$.startupTimeoutMs??5000,Z=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(f)throw f;let E=await fw(w);if(E!==null&&n$(E))return H("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((F)=>setTimeout(F,Z))}if(f)throw f;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function Hj($={}){let w=$.rpxDir??U0(),A=$.verbose??!1,J=$.timeoutMs??5000,U=$.pollIntervalMs??50,Y=$.forceAfterTimeout??!0,f=await fw(w);if(f===null||!n$(f)){if(f!==null)await t1(w);return await Uw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:f,forced:!1}}try{x.kill(f,"SIGTERM")}catch(Z){if(Z.code==="ESRCH")return await t1(w),{stopped:!1,pid:f,forced:!1};throw Z}let W=Date.now()+J;while(Date.now()<W){if(!n$(f))return H("daemon",`daemon pid=${f} stopped cleanly`,A),{stopped:!0,pid:f,forced:!1};await new Promise((Z)=>setTimeout(Z,U))}if(!Y)throw Error(`rpx daemon (pid=${f}) did not exit within ${J}ms`);H("daemon",`daemon pid=${f} did not exit, escalating to SIGKILL`,A);try{x.kill(f,"SIGKILL")}catch(Z){if(Z.code!=="ESRCH")throw Z}return await t1(w),await qw({rpxDir:w,verbose:A}).catch((Z)=>{H("daemon",`DNS teardown after SIGKILL: ${Z}`,A)}),{stopped:!0,pid:f,forced:!0}}async function Tj($={}){let w=$.rpxDir??U0();if(await IU(w))return;await Uw({rpxDir:w,verbose:$.verbose})}r0();Y$();import{spawn as Oq}from"node:child_process";import*as Nw from"node:process";class Gj{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){H("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Nw.cwd();H("start",`Starting process ${$}:`,A),H("start",` Command: ${J} ${U.join(" ")}`,A),H("start",` Working directory: ${Y}`,A),H("start",` Environment variables: ${J0(w.env)}`,A);let f=Oq(J,U,{cwd:Y,env:{...Nw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:Y,process:f,env:w.env}),new Promise((W,Z)=>{if(f.on("error",(B)=>{if(!this.isShuttingDown)H("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),Z(B),Nw.emit("SIGINT")}),f.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)H("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),Z(Error(`Process ${$} exited with code ${B}`)),Nw.emit("SIGINT")}),A)f.stdout?.on("data",(B)=>{H("process",`[${$}] ${B.toString().trim()}`,!0)}),f.stderr?.on("data",(B)=>{H("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),Z(Error(`Process ${$} was killed during startup`));else H("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){H("start",`No process found for ${$}`,w);return}return H("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),H("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){H("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){H("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){H("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,H("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{K.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var yU=new Gj;Y$();import*as u$ from"node:fs/promises";import{homedir as Xq}from"node:os";import*as lf from"node:path";import*as pf from"node:process";var _q=/^[a-zA-Z0-9._-]+$/;function Kw(){return lf.join(Xq(),".stacks","rpx","registry.d")}function q1($){return typeof $==="string"&&$.length>0&&$.length<=128&&_q.test($)}function tf($,w){if(!q1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return lf.join($,`${w}.json`)}function hj($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0;return typeof w.id==="string"&&q1(w.id)&&typeof w.from==="string"&&w.from.length>0&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function Dq($){await u$.mkdir($,{recursive:!0})}async function qj($,w=Kw(),A){if(!hj($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Dq(w);let J=tf(w,$.id),U=`${J}.tmp.${pf.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await u$.writeFile(U,Y,{encoding:"utf8",mode:420}),await u$.rename(U,J),H("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await u$.unlink(U).catch(()=>{}),f}}async function Nj($,w=Kw(),A){let J=tf(w,$);try{await u$.unlink(J),H("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function rf($,w=Kw(),A){let J=tf(w,$);try{let U=await u$.readFile(J,"utf8"),Y=JSON.parse(U);if(!hj(Y))return H("registry",`entry ${$} failed validation, removing`,A),await u$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return H("registry",`entry ${$} has invalid JSON, removing`,A),await u$.unlink(J).catch(()=>{}),null;throw U}}async function Kj($=Kw(),w){let A;try{A=await u$.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let J=[];for(let U of A){if(!U.endsWith(".json"))continue;let Y=U.slice(0,-5);if(!q1(Y))continue;let f=await rf(Y,$,w);if(f)J.push(f)}return J}r0();import{execSync as iq}from"node:child_process";import*as yw from"node:http";import*as Vj from"node:http2";import*as Oj from"node:net";import*as e from"node:process";var CU=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,h0={bold:CU(1,22),dim:CU(2,22),green:CU(32,39),cyan:CU(36,39)};x8();kf();r0();g1();Y$();import*as Rj from"node:fs";import*as Mj from"node:path";import*as q0 from"node:process";function kq($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function af($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,U=$.proxies.map((z)=>{let j=z.id??kq(z.to);if(!d1(j))throw Error(`invalid registry id "${j}" derived from to="${z.to}"`);if(J.has(j))throw Error(`duplicate registry id "${j}" — set an explicit \`id\` on one of the proxies`);return J.add(j),{...z,id:j}}),Y=new Date().toISOString();for(let z of U)await rF({id:z.id,from:z.from,to:z.to,pid:$.persistent?void 0:q0.pid,cwd:q0.cwd(),createdAt:Y,cleanUrls:z.cleanUrls,changeOrigin:z.changeOrigin,pathRewrites:z.pathRewrites},A,w);let f=await oF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let z of U)K.success(`https://${z.to} → ${z.from}`);if(K.info(`(via rpx daemon pid=${f.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,Z=A??Jw(),B=U.map((z)=>z.id),E=async()=>{if(W)return;W=!0;for(let z of B)await _f(z,A,w).catch((j)=>{H("runner",`removeEntry(${z}) failed: ${j}`,w)})},F=(z)=>{H("runner",`received ${z}, unregistering ${B.length} entries`,w),E().finally(()=>q0.exit(0))};q0.once("SIGINT",F),q0.once("SIGTERM",F),q0.once("exit",()=>{if(W)return;for(let z of B)try{Rj.unlinkSync(Mj.join(Z,`${z}.json`))}catch{}}),await new Promise(()=>{})}Y$();import{exec as Qq}from"node:child_process";import Rw from"node:fs";import yj from"node:os";import of from"node:path";import*as r1 from"node:process";import{promisify as xq}from"node:util";var LU=xq(Qq);function Ij($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var Y0=r1.platform==="win32"?of.join(r1.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",sf=!1;async function SU($){if(r1.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Hw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:J}=await LU(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return sf=!0,J}if(sf)try{let{stdout:J}=await LU(`sudo -n sh -c '${A}'`);return J}catch(J){H("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:J}=await LU(`sudo -n sh -c '${A}'`);return sf=!0,J}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(J){throw Error(`Failed to execute sudo command: ${J.message}`)}}async function a1($,w){let A=$.filter((U)=>!Ij(U)),J=$.filter((U)=>Ij(U));if(J.length>0)H("hosts",`Skipping /etc/hosts for loopback dev names: ${J.join(", ")}`,w);if(A.length===0)return;H("hosts",`Adding hosts: ${A.join(", ")}`,w),H("hosts",`Using hosts file at: ${Y0}`,w);try{let U;try{U=await Rw.promises.readFile(Y0,"utf-8")}catch{H("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{U=await SU(`cat "${Y0}"`)}catch(Z){throw console.log(" Could not read hosts file — skipping hosts setup"),H("hosts",`sudo read also failed: ${Z}`,w),Error(`Cannot read hosts file: ${Z}`)}}let Y=A.filter((Z)=>{let B=`127.0.0.1 ${Z}`,E=`::1 ${Z}`;return!U.includes(B)&&!U.includes(E)});if(Y.length===0){H("hosts","All hosts already exist in hosts file",w);return}let f=Y.map((Z)=>`
|
|
234
|
+
`)),this.enableDidYouMean){let w=[];for(let Y of this.commands){if(Y.displayName)w.push(Y.displayName);if(Y.aliasNames)w.push(...Y.aliasNames)}let A=oJ($,w);if(A.length>0)console.log(_1.yellow("Did you mean one of these?")),A.forEach((Y)=>console.log(` ${_1.dim("•")} ${this.name} ${Y}`)),console.log("")}console.log(_1.dim("Run"),`${this.name} --help`,_1.dim("to see all available commands")),a0.exit(1)}async parse($=lJ,w={}){let{run:A=!0,exitOnError:Y=!1}=w;if(Y)try{return await this.parse($,{run:A})}catch(J){throw this.handleUsageError(J),J}if(this.rawArgs=$,!this.name)this.name=$[1]?pF($[1]):"cli";let f=!0,X=$.slice(2),U=X[0];if(U&&!U.startsWith("-")){for(let J of this.commands)if(J.isMatched(U)){let B=this.mri(X,J);f=!1;let E={...B,args:B.args.slice(1)};this.setParsedInfo(E,J,U),this.emit(`command:${U}`,J);break}}if(f){for(let J of this.commands)if(J.name===""){f=!1;let B=this.mri(X,J);this.setParsedInfo(B,J),this.emit("command:!",J);break}}if(f){let J=this.mri($.slice(2));this.setParsedInfo(J)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),A=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),A=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(A)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return W}mri($,w){let A=[...this.globalCommand.options,...w?w.options:[]],Y=dF(A),f=[],X=$.indexOf("--");if(X>-1)f=$.slice(X+1),$=$.slice(0,X);let U=vF($,Y),W={_:U._};for(let T of Object.keys(U))if(T!=="_")W[sJ(T)]=U[T];let J=W._,B={"--":f},E=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,j=Object.create(null);for(let T of A){if(!E&&T.config.default!==void 0)for(let F of T.names)B[F]=T.config.default;if(Array.isArray(T.config.type)){if(j[T.name]===void 0)j[T.name]={shouldTransform:!0,transformFunction:T.config.type[0]}}}for(let T of Object.keys(W))if(T!=="_"){let F=T.split(".");gF(B,F,W[T]),tF(B,j)}return{args:J,options:B}}async run($=lJ){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let Y=$,f=Y.message??"command-line error",X=this.name?`${this.name}: `:"",U=/--help/.test(f)?"":`
|
|
235
|
+
Run \`${this.name??"cli"} --help\` for usage.`;a0.stderr.write(`${X}${f}${U}
|
|
236
|
+
`),a0.exit(Y.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let Y=[];A.args.forEach((W,J)=>{if(W.variadic)Y.push($.slice(J));else Y.push($[J])}),Y.push(w);let f={command:A,args:Y,options:w};for(let W of A.beforeHooks)await W(f);let X,U=async()=>{let W=A.commandAction.apply(this,Y);if(W instanceof Promise)X=await W;else X=W;return X};if(A.middleware.length>0){let W=0,J=async()=>{if(W<A.middleware.length){let B=A.middleware[W++];await B({...f,next:J})}else await U()};await J()}else await U();for(let W of A.afterHooks)await W(f);return X}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return a0.removeAllListeners("SIGINT"),a0.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 $W{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,A=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:A})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,A]of this.cache.entries())if($-A.timestamp>A.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var x7=new $W;function Az(){if("FORCE_COLOR"in D1.env)return D1.env.FORCE_COLOR!=="0";if("NO_COLOR"in D1.env||D1.env.TERM==="dumb")return!1;if(D1.platform==="win32")return!0;return gJ.isatty(1)&&gJ.isatty(2)}var wW=Az();function e($,w){if(!wW)return(A)=>A;return(A)=>$+A+w}var Yz=e("\x1B[0m","\x1B[0m"),fz=e("\x1B[31m","\x1B[39m"),Xz=e("\x1B[32m","\x1B[39m"),Uz=e("\x1B[33m","\x1B[39m"),Jz=e("\x1B[34m","\x1B[39m"),Wz=e("\x1B[35m","\x1B[39m"),Bz=e("\x1B[36m","\x1B[39m"),Ez=e("\x1B[37m","\x1B[39m"),jz=e("\x1B[90m","\x1B[39m"),Tz=e("\x1B[1m","\x1B[22m"),Fz=e("\x1B[3m","\x1B[23m"),zz=e("\x1B[4m","\x1B[24m"),hz=e("\x1B[2m","\x1B[22m"),Hz=e("\x1B[7m","\x1B[27m"),Gz=e("\x1B[8m","\x1B[28m"),Kz=e("\x1B[9m","\x1B[29m"),Rz=e("\x1B[41m","\x1B[49m"),qz=e("\x1B[42m","\x1B[49m"),Nz=e("\x1B[43m","\x1B[49m"),yz=e("\x1B[44m","\x1B[49m"),Mz=e("\x1B[45m","\x1B[49m"),Iz=e("\x1B[46m","\x1B[49m"),Cz=e("\x1B[47m","\x1B[49m"),Sz=wW,Lz={reset:Yz,red:fz,green:Xz,yellow:Uz,blue:Jz,magenta:Wz,cyan:Bz,white:Ez,gray:jz,bold:Tz,italic:Fz,underline:zz,dim:hz,inverse:Hz,hidden:Gz,strikethrough:Kz,bgRed:Rz,bgGreen:qz,bgYellow:Nz,bgBlue:yz,bgMagenta:Mz,bgCyan:Iz,bgWhite:Cz,isColorSupported:Sz},NA=Lz,Vz=["up","down","left","right","space","enter","cancel"],yA={actions:new Set(Vz),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function AW($,w){if(typeof $==="string")return yA.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(AW(A,w))return!0}return!1}function Qz($,w){if($===w)return[];let A=$.split(`
|
|
237
|
+
`),Y=w.split(`
|
|
238
|
+
`),f=[];for(let X=0;X<Math.max(A.length,Y.length);X++)if(A[X]!==Y[X])f.push(X);return f}var n7=Oz.platform.startsWith("win"),tJ=Symbol("clapp:cancel");function KA($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function Zz($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function xz($){return Zz($).length}function rJ($,w,A){if(!w||w<1)return $;let Y=A?.hard??!1,f=A?.trim??!0,X=$.split(`
|
|
239
|
+
`),U=[];for(let W of X){if(xz(W)<=w){U.push(f?W.trimEnd():W);continue}if(Y){let J="",B=0,E=0;while(E<W.length){let j=W.slice(E).match(/^\x1b\[[0-9;]*m/);if(j){J+=j[0],E+=j[0].length;continue}if(B>=w)U.push(f?J.trimEnd():J),J="",B=0;J+=W[E],B++,E++}if(J)U.push(f?J.trimEnd():J)}else U.push(f?W.trimEnd():W)}return U.join(`
|
|
240
|
+
`)}class FX{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,w=!0){let{input:A=_z,output:Y=Dz,render:f,signal:X,...U}=$;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=f.bind(this),this._track=w,this._abortSignal=X,this.input=A,this.output=Y}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let A=this._subscribers.get($)??[];A.push(w),this._subscribers.set($,A)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let A=this._subscribers.get($)??[],Y=[];for(let f of A)if(f.cb(...w),f.once)Y.push(()=>A.splice(A.indexOf(f),1));for(let f of Y)f();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(tJ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=kz.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),KA(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(I0.show),this.output.off("resize",this.render),KA(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(I0.show),this.output.off("resize",this.render),KA(this.input,!1),$(tJ)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let A=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!A&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Y=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Y)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&yA.aliases.has(w.name))this.emit("cursor",yA.aliases.get(w.name));if(yA.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let A=this.opts.validate(this.value);if(A)this.error=A instanceof Error?A.message:A,this.state="error"}if(this.state!=="error")this.state="submit"}if(AW([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
241
|
+
`),KA(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=rJ(this._prevFrame,pJ.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
242
|
+
`).length-1;this.output.write(I0.move(-999,$*-1))}render(){let $=rJ(this._render(this)??"",pJ.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(I0.hide);else{let w=Qz(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(I0.move(0,A)),this.output.write(JX.lines(1));let Y=$.split(`
|
|
243
|
+
`);this.output.write(Y[A]),this._prevFrame=$,this.output.write(I0.move(0,Y.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(I0.move(0,A)),this.output.write(JX.down());let f=$.split(`
|
|
244
|
+
`).slice(A);this.output.write(f.join(`
|
|
245
|
+
`)),this._prevFrame=$;return}this.output.write(JX.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function Pz($,w){if($===void 0)return 0;if(w.length===0)return 0;let Y=w.findIndex((f)=>f.value===$);return Y!==-1?Y:0}function iz($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function bz($,w){if(!w)return;if($)return w;return w[0]}class cz extends FX{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#Y;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return NA.inverse(NA.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...A]=this.userInput.slice(this._cursor);return`${$}${NA.inverse(w)}${A.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#Y=$.filter??iz;let A;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)A=$.initialValue;else A=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)A=[this.options[0].value];if(A)for(let Y of A){let f=w.findIndex((X)=>X.value===Y);if(f!==-1)this.toggleSelected(Y),this.#$=f}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Y,f)=>this.#f(Y,f)),this.on("userInput",(Y)=>this.#X(Y))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#f($,w){let A=w.name==="up",Y=w.name==="down",f=w.name==="return";if(A||Y){if(this.#$=Math.max(0,Math.min(this.#$+(A?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(f)this.value=bz(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#X($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#Y($,A));else this.filteredOptions=[...w];if(this.#$=Pz(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class uz extends FX{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),A=this.value;if(A===void 0)return!1;return w.every((Y)=>A.includes(Y.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),A=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((Y)=>A.findIndex((f)=>f.value===Y)===-1);else this.value=[...this.value,...A.map((Y)=>Y.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((A)=>A!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([A,Y])=>[{value:A,group:!0,label:A},...Y.map((f)=>({...f,group:A}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:A})=>A===$.cursorAt),this.#$?0:1),this.on("cursor",(A)=>{switch(A){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Y=this.options[this.cursor]?.group===!0;if(!this.#$&&Y)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Y=this.options[this.cursor]?.group===!0;if(!this.#$&&Y)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var nz=rF();var r=($,w)=>nz?$:w,d7=r("◆","*"),l7=r("■","x"),g7=r("▲","x"),t7=r("◇","o"),p7=r("┌","T"),vz=r("│","|"),r7=r("└","—"),a7=r("●",">"),s7=r("○"," "),o7=r("◻","[•]"),e7=r("◼","[+]"),$R=r("◻","[ ]"),wR=r("▪","•"),AR=r("─","-"),YR=r("╮","+"),fR=r("├","+"),XR=r("╯","+"),UR=r("●","•"),JR=r("◆","*"),WR=r("▲","!"),BR=r("■","x");var ER={light:r("─","-"),heavy:r("━","="),block:r("█","#")};function mz(){return`${NA.gray(vz)} `}var jR=mz();w8();import{homedir as A8}from"node:os";import{join as Y8,resolve as $N}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",eh={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Y8(A8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Y8(A8(),".stacks","ssl","stacks.localhost.crt"),keyPath:Y8(A8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var pw=eh;$w();kf();Zf();WJ();EJ();AA();WA();S1();X$();import{spawn as EF}from"node:child_process";import*as N0 from"node:fs/promises";import{homedir as SJ}from"node:os";import*as B0 from"node:path";import*as x from"node:process";var r6=5000;function E0(){return B0.join(SJ(),".stacks","rpx")}function zw($=E0()){return B0.join($,"daemon.pid")}async function Fw($=E0()){try{let w=await N0.readFile(zw($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function tf($=E0()){let w=await Fw($);return w!==null&&l$(w)}async function a6($=E0()){await N0.mkdir($,{recursive:!0});let w=zw($);while(!0){try{let Y=await N0.open(w,"wx");try{await Y.write(`${x.pid}
|
|
246
|
+
`)}finally{await Y.close()}return w}catch(Y){if(Y.code!=="EEXIST")throw Y}let A=await Fw($);if(A!==null&&l$(A))throw Error(`rpx daemon already running (pid=${A})`);await N0.unlink(w).catch(()=>{})}}async function jA($=E0()){await N0.unlink(zw($)).catch(()=>{})}function s6($){let w=$.cleanUrls??!1;if($.static)return{static:wA($.static,w),cleanUrls:w};let A=$.from??"localhost:1";return{sourceHost:new URL(A.startsWith("http")?A:`http://${A}`).host,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites}}function o6($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function e6($,w){let A=await Mw(w,$.verbose),Y=[...new Set(A.map((E)=>E.to))],f=o6(Y),X=[...new Set([f,...Y,"rpx.localhost"])],U=B0.join(SJ(),".stacks","ssl"),W=B0.join(U,"rpx.localhost.crt"),J={https:typeof $.https==="object"?{...$.https,certPath:W,keyPath:B0.join(U,"rpx.localhost.key"),commonName:f}:{certPath:W,keyPath:B0.join(U,"rpx.localhost.key"),caCertPath:B0.join(U,"rpx.localhost.ca.crt"),commonName:f},verbose:$.verbose,regenerateUntrustedCerts:!0,...X.length>1?{proxies:X.map((E)=>({from:"localhost:1",to:E}))}:{to:f,from:"localhost:1"}},B=await g0(J);if(!B)z("daemon","no usable cert on disk, generating one",$.verbose),await C1(J),B=await g0(J);if(!B)throw Error("failed to bootstrap TLS for rpx daemon");return B}async function $7($,w,A,Y){let f=x.env.SUDO_PASSWORD,X=x.env.HOME??SJ(),U=[x.execPath,...x.argv.slice(1)],W=[`HOME=${X}`,`PATH=${x.env.PATH??""}`];if(Y)W.push("RPX_VERBOSE=1");let J=f?["-S","-p","","env",...W,...U]:["-n","env",...W,...U];z("daemon",`elevating daemon via sudo for privileged ports ${w}/${A}`,Y);let B=EF("sudo",J,{detached:!0,stdio:["pipe","ignore","ignore"]}),E=null,j=null;if(B.once("error",(H)=>{E=H}),B.once("exit",(H)=>{j=H??0}),f&&B.stdin)B.stdin.write(`${f}
|
|
247
|
+
`),B.stdin.end();B.unref();let T=zw($),F=Date.now()+15000;while(Date.now()<F){if(E)throw E;let H=await Fw($);if(H!==null&&l$(H)){if(Y)q.success(`rpx daemon elevated to root (pid=${H}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:T,done:Promise.resolve(),stop:async()=>{try{x.kill(H,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(j!==null&&j!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${j}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((h)=>setTimeout(h,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}async function jF($={}){let w=$.verbose??!1,A=$.rpxDir??E0(),Y=$.registryDir??B0.join(A,"registry.d"),f=$.httpsPort??443,X=$.httpPort??80,U=$.hostname??"0.0.0.0",W=$.gcIntervalMs??r6,J=f>0&&f<1024||X>0&&X<1024,B=typeof x.getuid==="function"&&x.getuid()===0;if(x.platform!=="win32"&&J&&!B)return $7(A,f,X,w);let E=await a6(A),j=new Map,T=(L)=>XA(j,L);function F(L){let p=new Map;for(let T0 of L)p.set(T0.to,s6(T0));j=p,z("daemon",`routing table now covers ${p.size} host(s): ${Array.from(p.keys()).join(", ")||"<empty>"}`,w)}await uf(Y,w).catch((L)=>{z("daemon",`initial gc failed: ${L}`,w)});let H=await Mw(Y,w);F(H),await jw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS reconcile on start failed: ${L}`,w)}),await EA(H,{rpxDir:A,verbose:w,ownerPid:x.pid}).catch((L)=>{z("daemon",`DNS setup on start failed: ${L}`,w)});let h=[];if($.productionCerts){if(h=await JJ($.productionCerts,w),w&&h.length>0)q.info(`SNI: serving ${h.length} real cert(s): ${h.map((L)=>L.serverName).join(", ")}`)}let G=YA(T,w),K=fA(w),R=null;if(h.length===0)R=await e6($,Y);let M=$.onDemandTls,N=M?.enabled?new Pf({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??B0.join(A,"on-demand-certs"),initial:h,verbose:w,onCertAdded:(L)=>{d$(L)}}):null;function y(L){if(L.length>0)return L.map((p)=>({serverName:p.serverName,cert:p.cert,key:p.key}));return{key:R.key,cert:R.cert,ca:R.ca,requestCert:!1,rejectUnauthorized:!1}}function S(L){return Bun.serve({port:f,hostname:U,tls:y(L),fetch(p,T0){return G(p,T0)},websocket:K,error(p){return z("daemon",`https server error: ${p}`,w),new Response(`Server Error: ${p.message}`,{status:500})}})}let w$=S(N?N.sniEntries():h);async function d$(L){if(Zw)return;z("daemon",`rebuilding :443 with ${L.length} SNI cert(s)`,w),w$.stop(!1);let p;for(let T0=0;T0<20&&!Zw;T0++)try{w$=S(L);return}catch(GA){p=GA,await new Promise((xF)=>setTimeout(xF,25))}q.error(`rpx: failed to rebuild :443 after issuing cert: ${p?.message}`)}let _$=null;if(X>0)_$=Bun.serve({port:X,hostname:U,fetch(L){let p=new URL(L.url),T0=(L.headers.get("host")??p.hostname).split(":")[0];if(N&&p.pathname.startsWith("/.well-known/acme-challenge/")){let GA=N.challengeStore.handlePath(p.pathname);if(GA!==void 0)return new Response(GA,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(N&&!N.hasCert(T0))N.ensureCert(T0).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${T0}${p.pathname}${p.search}`}})}});if(w)q.success(`rpx daemon listening on https://${U}:${f}${_$?` (http→https on :${X})`:""}`),q.info(`pid file: ${E}`),q.info(`registry: ${Y}`);let Dw=zJ((L)=>{F(L),EA(L,{rpxDir:A,verbose:w,ownerPid:x.pid}).catch((p)=>{z("daemon",`DNS sync on registry change failed: ${p}`,w)})},{dir:Y,verbose:w}),kw=setInterval(()=>{uf(Y,w).then((L)=>{if(L>0)z("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{z("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof kw.unref==="function")kw.unref();let Zw=!1,V1,r0=new Promise((L)=>{V1=L});async function cJ(){if(Zw)return r0;if(Zw=!0,clearInterval(kw),Dw.close(),w$.stop(!1),_$?.stop(!1),await Cw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS teardown failed: ${L}`,w)}),await jA(A),w)q.info("rpx daemon stopped");return V1(),r0}let uJ=(L)=>{z("daemon",`received ${L}, shutting down`,w),cJ().catch(()=>{})};return x.once("SIGINT",uJ),x.once("SIGTERM",uJ),{stop:cJ,done:r0,httpsPort:typeof w$.port==="number"?w$.port:f,httpPort:_$&&typeof _$.port==="number"?_$.port:X,pidPath:E,ensureCert:(L)=>N?N.ensureCert(L):Promise.resolve(!1)}}function w7(){let $=x.execPath,w=B0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&x.argv[1])return[$,x.argv[1],"daemon:start"];return[$,"daemon:start"]}async function TF($={}){let w=$.rpxDir??E0(),A=$.verbose??!1;await jw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await Fw(w);if(Y!==null&&l$(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await jA(w);await N0.mkdir(w,{recursive:!0});let f=$.spawnCommand??w7();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=EF(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??x.cwd(),env:$.spawnEnv?{...x.env,...$.spawnEnv}:x.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await Fw(w);if(E!==null&&l$(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function FF($={}){let w=$.rpxDir??E0(),A=$.verbose??!1,Y=$.timeoutMs??5000,f=$.pollIntervalMs??50,X=$.forceAfterTimeout??!0,U=await Fw(w);if(U===null||!l$(U)){if(U!==null)await jA(w);return await jw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{x.kill(U,"SIGTERM")}catch(J){if(J.code==="ESRCH")return await jA(w),{stopped:!1,pid:U,forced:!1};throw J}let W=Date.now()+Y;while(Date.now()<W){if(!l$(U))return z("daemon",`daemon pid=${U} stopped cleanly`,A),{stopped:!0,pid:U,forced:!1};await new Promise((J)=>setTimeout(J,f))}if(!X)throw Error(`rpx daemon (pid=${U}) did not exit within ${Y}ms`);z("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,A);try{x.kill(U,"SIGKILL")}catch(J){if(J.code!=="ESRCH")throw J}return await jA(w),await Cw({rpxDir:w,verbose:A}).catch((J)=>{z("daemon",`DNS teardown after SIGKILL: ${J}`,A)}),{stopped:!0,pid:U,forced:!0}}async function zF($={}){let w=$.rpxDir??E0();if(await tf(w))return;await jw({rpxDir:w,verbose:$.verbose})}$w();X$();import{spawn as A7}from"node:child_process";import*as Sw from"node:process";class hF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||Sw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${J0(w.env)}`,A);let U=A7(Y,f,{cwd:X,env:{...Sw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),Sw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),Sw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var pf=new hF;X$();import*as v$ from"node:fs/promises";import{homedir as Y7}from"node:os";import*as LJ from"node:path";import*as OJ from"node:process";var f7=/^[a-zA-Z0-9._-]+$/;function Lw(){return LJ.join(Y7(),".stacks","rpx","registry.d")}function O1($){return typeof $==="string"&&$.length>0&&$.length<=128&&f7.test($)}function VJ($,w){if(!O1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return LJ.join($,`${w}.json`)}function HF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string";return typeof w.id==="string"&&O1(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function X7($){await v$.mkdir($,{recursive:!0})}async function GF($,w=Lw(),A){if(!HF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await X7(w);let Y=VJ(w,$.id),f=`${Y}.tmp.${OJ.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await v$.writeFile(f,X,{encoding:"utf8",mode:420}),await v$.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await v$.unlink(f).catch(()=>{}),U}}async function KF($,w=Lw(),A){let Y=VJ(w,$);try{await v$.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function QJ($,w=Lw(),A){let Y=VJ(w,$);try{let f=await v$.readFile(Y,"utf8"),X=JSON.parse(f);if(!HF(X))return z("registry",`entry ${$} failed validation, removing`,A),await v$.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await v$.unlink(Y).catch(()=>{}),null;throw f}}async function RF($=Lw(),w){let A;try{A=await v$.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!O1(X))continue;let U=await QJ(X,$,w);if(U)Y.push(U)}return Y}$w();import{execSync as j7}from"node:child_process";import*as _w from"node:http";import*as LF from"node:http2";import*as OF from"node:net";import*as $$ from"node:process";var rf=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,y0={bold:rf(1,22),dim:rf(2,22),green:rf(32,39),cyan:rf(36,39)};TU();hJ();$w();WA();X$();import*as qF from"node:fs";import*as NF from"node:path";import*as M0 from"node:process";function U7($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function _J($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,Y=new Set,f=$.proxies.map((T)=>{let F=T.id??U7(T.to);if(!JA(F))throw Error(`invalid registry id "${F}" derived from to="${T.to}"`);if(Y.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return Y.add(F),{...T,id:F}}),X=new Date().toISOString();for(let T of f)await pT({id:T.id,from:T.from,to:T.to,pid:$.persistent?void 0:M0.pid,cwd:M0.cwd(),createdAt:X,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,pathRewrites:T.pathRewrites,static:T.static},A,w);let U=await sT({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let T of f){let F=T.static?`static ${typeof T.static==="string"?T.static:T.static.dir}`:T.from;q.success(`https://${T.to} → ${F}`)}if(q.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,J=A??Ew(),B=f.map((T)=>T.id),E=async()=>{if(W)return;W=!0;for(let T of B)await FJ(T,A,w).catch((F)=>{z("runner",`removeEntry(${T}) failed: ${F}`,w)})},j=(T)=>{z("runner",`received ${T}, unregistering ${B.length} entries`,w),E().finally(()=>M0.exit(0))};M0.once("SIGINT",j),M0.once("SIGTERM",j),M0.once("exit",()=>{if(W)return;for(let T of B)try{qF.unlinkSync(NF.join(J,`${T}.json`))}catch{}}),await new Promise(()=>{})}X$();import{exec as J7}from"node:child_process";import Ow from"node:fs";import MF from"node:os";import kJ from"node:path";import*as TA from"node:process";import{promisify as W7}from"node:util";var af=W7(J7);function yF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var j0=TA.platform==="win32"?kJ.join(TA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",DJ=!1;async function sf($){if(TA.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Nw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:Y}=await af(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return DJ=!0,Y}if(DJ)try{let{stdout:Y}=await af(`sudo -n sh -c '${A}'`);return Y}catch(Y){z("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:Y}=await af(`sudo -n sh -c '${A}'`);return DJ=!0,Y}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(Y){throw Error(`Failed to execute sudo command: ${Y.message}`)}}async function FA($,w){let A=$.filter((f)=>!yF(f)),Y=$.filter((f)=>yF(f));if(Y.length>0)z("hosts",`Skipping /etc/hosts for loopback dev names: ${Y.join(", ")}`,w);if(A.length===0)return;z("hosts",`Adding hosts: ${A.join(", ")}`,w),z("hosts",`Using hosts file at: ${j0}`,w);try{let f;try{f=await Ow.promises.readFile(j0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{f=await sf(`cat "${j0}"`)}catch(J){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${J}`,w),Error(`Cannot read hosts file: ${J}`)}}let X=A.filter((J)=>{let B=`127.0.0.1 ${J}`,E=`::1 ${J}`;return!f.includes(B)&&!f.includes(E)});if(X.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=X.map((J)=>`
|
|
244
248
|
# Added by rpx
|
|
245
|
-
127.0.0.1 ${
|
|
246
|
-
::1 ${
|
|
247
|
-
`),W=
|
|
248
|
-
`),
|
|
249
|
+
127.0.0.1 ${J}
|
|
250
|
+
::1 ${J}`).join(`
|
|
251
|
+
`),W=kJ.join(MF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ow.promises.writeFile(W,f+U,"utf8"),await sf(`cat "${W}" | tee "${j0}" > /dev/null`),console.log(` Hosts updated: ${X.join(", ")}`)}catch(J){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),X.forEach((B)=>{console.log(` 127.0.0.1 ${B}`),console.log(` ::1 ${B}`)}),console.log(` Or run: sudo nano ${j0}`)}finally{try{await Ow.promises.unlink(W)}catch{}}}catch(f){z("hosts",`Failed to manage hosts file: ${f.message}`,w)}}async function IF($,w){z("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await Ow.promises.readFile(j0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await sf(`cat "${j0}"`)}catch(J){throw z("hosts",`sudo read also failed: ${J}`,w),Error(`Cannot read hosts file: ${J}`)}}let Y=A.split(`
|
|
252
|
+
`),f=!1,X=Y.filter((J)=>{if($.some((E)=>J.includes(` ${E}`)&&(J.includes("127.0.0.1")||J.includes("::1"))))return f=!0,!1;if(J.trim()==="# Added by rpx")return f=!0,!1;return!0});if(!f){z("hosts","No matching hosts found to remove",w);return}while(X[X.length-1]?.trim()==="")X.pop();let U=`${X.join(`
|
|
249
253
|
`)}
|
|
250
|
-
`,W=of.join(yj.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Rw.promises.writeFile(W,f,"utf8"),await SU(`cat "${W}" | tee "${Y0}" > /dev/null`),H("hosts","Hosts removed successfully",w)}catch(Z){H("hosts","Could not clean up hosts file automatically",w)}finally{try{await Rw.promises.unlink(W)}catch(Z){H("hosts",`Failed to remove temporary file: ${Z}`,w)}}}catch(A){H("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function s1($,w){H("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Rw.promises.readFile(Y0,"utf-8")}catch(J){H("hosts",`Error reading hosts file: ${J}`,w);try{let U=Hw(),Y;if(U)Y=`echo '${U}' | sudo -S cat "${Y0}" 2>/dev/null`;else Y=`sudo -n cat "${Y0}" 2>/dev/null || cat "${Y0}" 2>/dev/null || echo ""`;let{stdout:f}=await LU(Y);A=f}catch(U){return H("hosts",`Cannot read hosts file, assuming entries don't exist: ${U}`,w),$.map(()=>!1)}}return $.map((J)=>{let U=`127.0.0.1 ${J}`,Y=`::1 ${J}`;return A.includes(U)||A.includes(Y)})}jU();Y$();import*as VU from"node:net";function Mw($,w,A){return H("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let U=VU.createServer(),Y=setTimeout(()=>{H("port",`Checking port ${$} timed out, assuming it's in use`,A),U.close(),J(!0)},3000);U.once("error",(f)=>{if(clearTimeout(Y),f.code==="EADDRINUSE")H("port",`Port ${$} is in use`,A),J(!0);else H("port",`Error checking port ${$}: ${f.message}`,A),J(!0)}),U.once("listening",()=>{clearTimeout(Y),H("port",`Port ${$} is available`,A),U.close(),J(!1)});try{U.listen($,w)}catch(f){clearTimeout(Y),H("port",`Exception checking port ${$}: ${f}`,A),J(!0)}})}async function Pq($,w,A,J=50){H("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let U=$,Y=0;while(Y<J){if(Y++,!await Mw(U,w,A))return H("port",`Found available port: ${U} after ${Y} attempts`,A),U;H("port",`Port ${U} is in use, trying ${U+1} (attempt ${Y}/${J})`,A),U++}throw Error(`Unable to find available port after ${J} attempts starting from ${$}`)}function Lj($,w,A=5000,J){return H("port",`Testing connection to ${w}:${$}`,J),new Promise((U)=>{let Y=VU.connect({host:w,port:$,timeout:A});Y.once("connect",()=>{H("port",`Successfully connected to ${w}:${$}`,J),Y.end(),U(!0)}),Y.once("timeout",()=>{H("port",`Connection to ${w}:${$} timed out`,J),Y.destroy(),U(!1)}),Y.once("error",(f)=>{H("port",`Failed to connect to ${w}:${$}: ${f.message}`,J),Y.destroy(),U(!1)})})}class OU{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,A=50){this.hostname=$,this.verbose=w,this.maxRetries=A}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Mw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await Lj($,this.hostname,3000,this.verbose))return H("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await Pq($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await Lj(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){H("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var YC=new OU;r0();Y$();import{spawn as bq}from"node:child_process";import*as Iw from"node:process";class XU{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){H("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Iw.cwd();H("start",`Starting process ${$}:`,A),H("start",` Command: ${J} ${U.join(" ")}`,A),H("start",` Working directory: ${Y}`,A),H("start",` Environment variables: ${J0(w.env)}`,A);let f=bq(J,U,{cwd:Y,env:{...Iw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:Y,process:f,env:w.env}),new Promise((W,Z)=>{if(f.on("error",(B)=>{if(!this.isShuttingDown)H("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),Z(B),Iw.emit("SIGINT")}),f.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)H("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),Z(Error(`Process ${$} exited with code ${B}`)),Iw.emit("SIGINT")}),A)f.stdout?.on("data",(B)=>{H("process",`[${$}] ${B.toString().trim()}`,!0)}),f.stderr?.on("data",(B)=>{H("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),Z(Error(`Process ${$} was killed during startup`));else H("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){H("start",`No process found for ${$}`,w);return}return H("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),H("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){H("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){H("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){H("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,H("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{K.error(`Failed to stop process ${A}:`,J)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var EC=new XU;zU();Y$();var DU=new XU,cq="0.12.0",uq=new OU("0.0.0.0"),o1=new Set,ef=!1,_U=null,$Z=null;async function kU($){if(ef)return H("cleanup","Cleanup already in progress, skipping",$?.verbose),$Z||Promise.resolve();ef=!0,H("cleanup","Starting cleanup process",$?.verbose),$Z=new Promise((w)=>{_U=w});try{await DU.stopAll($?.verbose),K.info("Shutting down proxy servers...");let w=[],A=Array.from(o1).map((J)=>new Promise((U)=>{J.close(()=>{H("cleanup","Server closed successfully",$?.verbose),U()})}));if(w.push(...A),$?.hosts&&$.domains?.length){H("cleanup","Cleaning up hosts file entries",$?.verbose),H("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(H("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)K.info("Cleaning up hosts file entries..."),w.push(Cj(J,$?.verbose).then(()=>{H("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((U)=>{H("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),K.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){H("cleanup","Cleaning up SSL certificates",$?.verbose),K.info("Cleaning up SSL certificates...");let J=$.domains.map(async(U)=>{try{await lF(U,$?.verbose),H("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(Y){H("cleanup",`Failed to remove certificates for ${U}: ${Y}`,$?.verbose),K.warn(`Failed to clean up certificates for ${U}:`,Y)}});w.push(...J)}await Promise.allSettled(w),H("cleanup","All cleanup tasks completed successfully",$?.verbose),K.success("All cleanup tasks completed successfully")}catch(w){H("cleanup",`Error during cleanup: ${w}`,$?.verbose),K.error("Error during cleanup:",w)}finally{if(_U)_U();_U=null,ef=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(e.env.NODE_ENV!=="test"&&e.env.BUN_ENV!=="test"&&!w)e.exit(0)}return $Z}var wZ=!1;function AZ($){if(wZ){H("signal",`Received second ${$} signal, forcing exit`,!0),e.exit(1);return}wZ=!0,H("signal",`Received ${$} signal, initiating cleanup`,!0),kU().catch((w)=>{H("signal",`Cleanup failed after ${$}: ${w}`,!0),e.exit(1)}).finally(()=>{wZ=!1})}e.once("SIGINT",()=>AZ("SIGINT"));e.once("SIGTERM",()=>AZ("SIGTERM"));e.on("uncaughtException",($)=>{H("process",`Uncaught exception: ${$}`,!0),K.error("Uncaught exception:",$),AZ("uncaughtException")});async function e1($,w,A,J=5){H("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let U=15000,Y=Date.now();if(e.env.RPX_BYPASS_CONNECTION_TEST==="true"){H("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let f=()=>new Promise((W,Z)=>{let B=Oj.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{H("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{H("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),Z(Error("Connection timed out"))}),B.once("error",(E)=>{H("connection",`Failed to connect to ${$}:${w}: ${E}`,A),B.destroy(),Z(E)})});try{await f()}catch(W){if(Date.now()-Y>U){H("connection",`Connection test timed out after ${U}ms, but continuing anyway`,A),K.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&J>0)return H("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),e1($,w,A,J-1);if(J>0)try{H("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((B,E)=>{let F=yw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(z)=>{H("connection",`Received HTTP response with status: ${z.statusCode}`,A),B()});F.on("error",(z)=>E(z)),F.on("timeout",()=>{F.destroy(),E(Error("HTTP request timed out"))}),F.end()}),H("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(B){return H("connection",`HTTP request to ${$}:${w} failed: ${B}`,A),H("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),e1($,w,A,J-1)}let Z=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${W.message}`;H("connection",`${Z}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),K.warn(Z),K.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 Xj($){H("server",`Starting server with options: ${J0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),J=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),U=[A.hostname];if(!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){H("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await s1(U,$.verbose))[0]){K.info(`Adding ${A.hostname} to hosts file...`),K.info("This may require sudo/administrator privileges");try{await a1(U,$.verbose)}catch(W){if(K.error("Failed to add hosts entry:",W.message),K.warn("You can manually add this entry to your hosts file:"),K.warn(`127.0.0.1 ${A.hostname}`),K.warn(`::1 ${A.hostname}`),e.platform==="win32")K.warn("On Windows:"),K.warn("1. Run notepad as administrator"),K.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else K.warn("On Unix systems:"),K.warn("sudo nano /etc/hosts")}}else H("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(f){K.error("Failed to check hosts file:",f.message)}}try{await e1(w.hostname,J,$.verbose)}catch(f){H("server",`Connection test failed: ${f}`,$.verbose),K.error(f.message),K.warn("Continuing with proxy setup despite connection test failure..."),K.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let Y=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=n1({...$,to:A.hostname});if(Y=await n0({...$,to:A.hostname,https:$.https}),!Y){if(H("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await T1({...$,from:w.toString(),to:A.hostname,https:$.https}),Y=await n0({...$,to:A.hostname,https:$.https}),!Y)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(f){throw H("server",`SSL setup failed: ${f}`,$.verbose),f}H("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await nq({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:Y})}async function vq($,w,A,J,U,Y,f,W,Z,B,E){H("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,Z);function F(T){let h={};for(let[q,N]of Object.entries(T))if(!q.startsWith(":"))h[q]=N;return h}let z=(T,h)=>{H("request",`Incoming request: ${T.method} ${T.url}`,Z);let q=T.url||"/",N=T.method||"GET";if(T instanceof Vj.Http2ServerRequest){let L=T.headers;N=L[":method"]||N,q=L[":path"]||q}if(B){if(!q.match(/\.[a-z0-9]+$/i))if(q.endsWith("/"))q=`${q}index.html`;else q=`${q}.html`}let R=F(T.headers);if(E)R.host=`${Y.hostname}:${A}`,H("request",`Changed origin: setting host header to ${R.host}`,Z);let y={hostname:Y.hostname,port:A,path:q,method:N,headers:R};H("request",`Proxy request options: ${J0(y)}`,Z);let C=yw.request(y,(L)=>{if(H("response",`Proxy response received with status ${L.statusCode}`,Z),B&&L.statusCode===404){let f0=[];if(q.endsWith(".html"))f0.push(q.slice(0,-5));else if(!q.match(/\.[a-z0-9]+$/i))f0.push(`${q}.html`);if(!q.endsWith("/"))f0.push(`${q}/index.html`);if(f0.length>0){H("cleanUrls",`Trying alternative paths: ${f0.join(", ")}`,Z);let S=(O$)=>{if(O$.length===0){h.writeHead(L.statusCode||404,L.headers),L.pipe(h);return}let Ww=O$[0],Pj={...y,path:Ww},JZ=yw.request(Pj,($A)=>{if($A.statusCode===200)H("cleanUrls",`Found matching path: ${Ww}`,Z),h.writeHead($A.statusCode,$A.headers),$A.pipe(h);else S(O$.slice(1))});JZ.on("error",()=>S(O$.slice(1))),JZ.end()};S(f0);return}}let N0={...L.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};h.writeHead(L.statusCode||500,N0),L.pipe(h)});C.on("error",(L)=>{H("request",`Proxy request failed: ${L}`,Z),K.error("Proxy request failed:",L),h.writeHead(502),h.end(`Proxy Error: ${L.message}`)}),T.pipe(C)};if(H("server",`Creating server with SSL config: ${!!f}`,Z),f)return new Promise((T,h)=>{try{let q=Bun.serve({port:J,hostname:U,tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(N){let R=new URL(N.url);H("request",`Bun.serve received: ${N.method} ${R.pathname}`,Z);let y=`http://${Y.host}`,C=new URL(R.pathname+R.search,y);try{let L=new Headers(N.headers);if(L.set("host",Y.host),E)L.set("origin",y);L.set("x-forwarded-for","127.0.0.1"),L.set("x-forwarded-proto","https"),L.set("x-forwarded-host",w);let N0=await fetch(C.toString(),{method:N.method,headers:L,body:N.body,redirect:"manual"}),f0=new Headers(N0.headers);if(B&&R.pathname.endsWith(".html")){let S=R.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:S}})}return new Response(N0.body,{status:N0.status,statusText:N0.statusText,headers:f0})}catch(L){return H("request",`Proxy error: ${L}`,Z),new Response(`Proxy Error: ${L}`,{status:502})}},error(N){return H("server",`Bun.serve error: ${N}`,Z),new Response(`Server Error: ${N.message}`,{status:500})}});o1.add(q),Sj({from:$,to:w,vitePluginUsage:W,listenPort:J,ssl:!0,cleanUrls:B,verbose:Z}),T()}catch(q){h(q)}});let j=yw.createServer(z);function G(T){return o1.add(T),new Promise((h,q)=>{T.listen(J,U,()=>{H("server",`Server listening on port ${J}`,Z),Sj({from:$,to:w,vitePluginUsage:W,listenPort:J,ssl:!!f,cleanUrls:B,verbose:Z}),h()}),T.on("error",(N)=>{H("server",`Server error: ${N}`,Z),q(N)})})}return G(j)}async function nq($){H("setup",`Setting up reverse proxy: ${J0($)}`,$.verbose);let{from:w,to:A,fromPort:J,sourceUrl:U,ssl:Y,verbose:f,cleanup:W,vitePluginUsage:Z,changeOrigin:B,cleanUrls:E}=$,F=80,z=443,j="0.0.0.0",G=$.portManager||uq;try{if(A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await s1([A],f))[0]){K.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await a1([A],f),K.success(`Added ${A} to your hosts file.`)}catch(R){K.error(`Failed to add ${A} to your hosts file: ${R}`),K.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(e.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await s1([A],f))[0]){H("hosts",`${A} not found in hosts file, adding...`,f);try{await a1([A],f)}catch(R){H("hosts",`Failed to add ${A} to hosts file: ${R}`,f)}}}if(Y&&!G.usedPorts.has(F)){if(!await Mw(F,j,f))H("setup","Starting HTTP redirect server",f),_j(f),G.usedPorts.add(F);else if(H("setup","Port 80 is in use, skipping HTTP redirect",f),f)K.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let T=Y?z:F,h=await Mw(T,j,f),q;if(h){if(H("setup",`Port ${T} is already in use`,f),f)K.warn(`Port ${T} is already in use. This may be another instance of rpx or another service.`);if(T===443){if(q=await G.getNextAvailablePort(3443,!0),H("setup",`Using port ${q} instead of ${T}`,f),f)K.info(`Using port ${q} instead. Access your site at https://${A}:${q}`)}else if(q=await G.getNextAvailablePort(T+1000,!0),H("setup",`Using port ${q} instead of ${T}`,f),f)K.info(`Using port ${q} instead. Access your site at http://${A}:${q}`)}else q=T,G.usedPorts.add(q),H("setup",`Using standard ${T===443?"HTTPS":"HTTP"} port ${T} for ${A}`,f);await vq(w,A,J,q,j,U,Y,Z,f,E,B)}catch(T){H("setup",`Setup failed: ${T}`,f),K.error(`Failed to setup reverse proxy: ${T.message}`),kU({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:f,vitePluginUsage:Z})}}function _j($){H("redirect","Starting HTTP redirect server",$);let w=yw.createServer((A,J)=>{let U=A.headers.host||"";H("redirect",`Redirecting request from ${U}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${U}${A.url}`}),J.end()}).listen(80);o1.add(w),H("redirect","HTTP redirect server started",$)}function Dj($){let w={...Q8,...$};if(H("proxy",`Starting proxy with options: ${J0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){K.error("viaDaemon mode requires both `from` and `to`");return}af({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((Z)=>{K.error(`Failed to register with rpx daemon: ${Z.message}`),e.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",U=e.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),Y=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"];if(U&&Y.includes(J)&&w?.verbose)K.warn(`The .${J} TLD may not work reliably for local development`),K.info(` Google owns .${J} with HSTS preloading, which can bypass local DNS`),K.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(U)Promise.resolve().then(() => (G1(),MU)).then(({setupDevelopmentDns:Z})=>{Z({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(f.includes(J))K.success(`DNS server started for .${J} domains`);else K.success(`DNS server started for .${J} domains (hosts file entry also added)`)});else H("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((Z)=>{H("dns",`Failed to start DNS server: ${Z}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:n1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};H("proxy",`Server options: ${J0(W)}`,w.verbose),Xj(W).catch((Z)=>{H("proxy",`Failed to start proxy: ${Z}`,w.verbose),K.error(`Failed to start proxy: ${Z.message}`),kU({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function mq($){return $?.verbose||!1}async function kj($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=mq(w);if(H("config",`Starting with config: ${J0(w,2)}`,A),H("config",`Is multi-proxy? ${"proxies"in w}`,A),w.viaDaemon){let G="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((T)=>({id:T.id,from:T.from,to:T.to,cleanUrls:T.cleanUrls??w.cleanUrls,changeOrigin:T.changeOrigin??w.changeOrigin,pathRewrites:T.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await af({proxies:G,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){H("servers",`Found ${w.proxies.length} proxies in config`,A);for(let j of w.proxies)if(j.start){let G=`${j.from}-${j.to}`;try{H("watch",`Starting command for ${G} with command: ${j.start.command}`,A),K.info(`Starting command for ${G}...`),await DU.startProcess(G,j.start,A);let T=new URL(j.from.startsWith("http")?j.from:`http://${j.from}`),h=T.hostname||"localhost",q=Number(T.port)||80;try{await e1(h,q,A),H("watch",`Dev server is ready at ${h}:${q}`,A)}catch(N){H("watch",`Connection check failed, but continuing with proxy setup: ${N}`,A),K.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw H("watch",`Failed to start command for ${G}: ${T}`,A),Error(`Failed to start command for ${G}: ${T}`)}}else H("watch",`No start command for proxy ${j.from} -> ${j.to}`,A)}else if("start"in w&&w.start){H("watch","Found start command in single proxy config",A);let j=`${w.from}-${w.to}`;try{if(w.start)H("watch",`Starting command: ${w.start.command}`,A),await DU.startProcess(j,w.start,A);let G=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),T=G.hostname||"localhost",h=Number(G.port)||80;try{await e1(T,h,A),H("watch",`Dev server is ready at ${T}:${h}`,A)}catch(q){H("watch",`Connection check failed, but continuing with proxy setup: ${q}`,A),K.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(G){throw H("watch",`Failed to run start command: ${G}`,A),Error(`Failed to run start command: ${G}`)}}else H("watch","No start command found in config",A);let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(e.platform!=="win32"&&(w.https||w.cleanup?.hosts!==!1)){if(!Hw())try{H("sudo","Pre-acquiring sudo credentials for privileged operations",A),iq("sudo -v",{stdio:"inherit"})}catch{H("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let j=await n0(w);if(!j){if(H("ssl",`No valid or trusted certificates found for ${J}, generating new ones`,w.verbose),await T1(w),j=await n0(w),!j)throw Error(`Failed to load SSL certificates after generation for ${J}`)}else H("ssl",`Using existing and trusted certificates for ${J}`,w.verbose);w._cachedSSLConfig=j}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((j)=>({...j,https:w.https,cleanup:w.cleanup,cleanUrls:j.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:j.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],Y=U.map((j)=>j.to||"rpx.localhost"),f=w._cachedSSLConfig,W=Y.filter((j)=>j&&!j.includes("localhost")&&!j.includes("127.0.0.1")),Z=["dev","app","page","new","day","foo"],B=["test","localhost","local","example","invalid"],E=[...new Set(W.map((j)=>j.split(".").pop()?.toLowerCase()))],F=E.filter((j)=>!!j&&Z.includes(j));if(F.length>0&&A)K.warn(`The following TLDs may not work reliably for local development: ${F.map((j)=>`.${j}`).join(", ")}`),K.info(" These TLDs have HSTS preloading which can bypass local DNS"),K.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(e.platform==="darwin"&&W.length>0){let{setupDevelopmentDns:j}=await Promise.resolve().then(() => (G1(),MU));if(await j({domains:W,verbose:A})){if(A)if(E.every((h)=>!!h&&B.includes(h)))K.success(`DNS server started for ${E.map((h)=>`.${h}`).join(", ")} domains`);else K.success(`DNS server started for ${E.map((h)=>`.${h}`).join(", ")} domains (hosts file entries also added)`)}else H("dns","Could not start DNS server - custom domains may not resolve",A)}let z=async()=>{H("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:j}=await Promise.resolve().then(() => (G1(),MU));await j({verbose:w.verbose})}catch(j){H("cleanup",`Error stopping DNS server: ${j}`,w.verbose)}try{await DU.stopAll(w.verbose)}catch(j){H("cleanup",`Error stopping processes: ${j}`,w.verbose)}await kU({domains:Y,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(e.on("SIGINT",z),e.on("SIGTERM",z),e.on("uncaughtException",(j)=>{H("process",`Uncaught exception: ${j}`,!0),console.error("Uncaught exception:",j),z()}),f&&U.length>1){H("proxies",`Creating shared HTTPS server for ${U.length} domains`,A);let j=new Map;for(let q of U){let N=q.to||"rpx.localhost",R=new URL(q.from?.startsWith("http")?q.from:`http://${q.from}`);if(j.set(N,{sourceHost:R.host,cleanUrls:q.cleanUrls||!1,changeOrigin:q.changeOrigin||!1,pathRewrites:q.pathRewrites}),H("proxies",`Route: ${N} → ${R.host}`,A),!N.includes("localhost")&&!N.includes("127.0.0.1"))try{if(!(await s1([N],A))[0])await a1([N],A)}catch{H("hosts",`Could not add hosts entry for ${N}`,A)}}if(!await Mw(80,"0.0.0.0",A))_j(A);let T=443;if(await Mw(T,"0.0.0.0",A)){if(H("proxies",`Port ${T} is already in use, cannot start shared proxy`,A),A)K.warn(`Port ${T} is in use. Shared HTTPS proxy cannot start.`);return}try{let q=Bun.serve({port:T,hostname:"0.0.0.0",tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},fetch:m1((N)=>j.get(N),A),error(N){return H("server",`Shared proxy server error: ${N}`,A),new Response(`Server Error: ${N.message}`,{status:500})}});o1.add(q),H("proxies",`Shared HTTPS proxy listening on port ${T} for ${j.size} domains`,A)}catch(q){H("proxies",`Failed to start shared proxy: ${q}`,A),console.error("Failed to start shared HTTPS proxy:",q),z()}}else for(let j of U)try{let G=j.to||"rpx.localhost";H("proxy",`Starting proxy for ${G} with SSL config: ${!!f}`,j.verbose),await Xj({from:j.from||"localhost:5173",to:G,cleanUrls:j.cleanUrls||!1,https:j.https||!1,cleanup:j.cleanup||!1,vitePluginUsage:j.vitePluginUsage||!1,verbose:j.verbose||!1,_cachedSSLConfig:f,changeOrigin:j.changeOrigin||!1})}catch(G){H("proxies",`Failed to start proxy for ${j.to}: ${G}`,j.verbose),console.error(`Failed to start proxy for ${j.to}:`,G),z()}}function Sj($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${h0.green(h0.bold("rpx"))} ${h0.green(`v${cq}`)}`),console.log(` ${h0.green("➜")} ${h0.dim($?.from??"")} ${h0.dim("➜")} ${h0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${h0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${h0.green("➜")} Clean URLs enabled`)}Nf();var VC=new zw("rpx",{showTags:!1});function Qj($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}v$.chdir(gq(dq(lq(import.meta.url)),".."));var d$=new nU("rpx"),xj="0.12.0";d$.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return kj(iw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(J){console.error("Failed to parse start-env JSON:",J),v$.exit(1)}w.start=A}return Dj(w)});d$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=Qj(iw)?iw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):iw.to===$?iw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),v$.exit(1);try{await yU.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(J){console.error(`Failed to start dev server for ${$}:`,J),v$.exit(1)}});d$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await yU.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),v$.exit(1)}});d$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await yU.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),v$.exit(1)}});d$.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("--verbose","Enable verbose logging").action(async($)=>{try{await(await jj({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,verbose:$.verbose??!0})).done,v$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),v$.exit(1)}});d$.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await Hj({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});d$.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??U0(),A=await fw(w),J=await IU(w),U=$.registryDir,Y=await Kj(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:Zw(w),rpxDir:w,registryDir:U??Kw(),entries:Y},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Zw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Zw(w)}`);if(console.log(`registry: ${U??Kw()}`),Y.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${Y.length}):`);for(let f of Y){let W=f.pid!==void 0?`, pid=${f.pid}`:"";console.log(` https://${f.to} \u2192 ${f.from} (id=${f.id}${W})`)}});d$.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),v$.exit(1);if(!q1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),v$.exit(1);try{await qj({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),v$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await zj({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),v$.exit(1)}});d$.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(!q1($))console.error(`invalid id: ${JSON.stringify($)}`),v$.exit(1);let A=await rf($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await Nj($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});d$.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??U0();if(await IU(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await Tj({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});d$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(xj)});d$.version(xj);d$.help();d$.run();
|
|
254
|
+
`,W=kJ.join(MF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Ow.promises.writeFile(W,U,"utf8"),await sf(`cat "${W}" | tee "${j0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(J){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Ow.promises.unlink(W)}catch(J){z("hosts",`Failed to remove temporary file: ${J}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function zA($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Ow.promises.readFile(j0,"utf-8")}catch(Y){z("hosts",`Error reading hosts file: ${Y}`,w);try{let f=Nw(),X;if(f)X=`echo '${f}' | sudo -S cat "${j0}" 2>/dev/null`;else X=`sudo -n cat "${j0}" 2>/dev/null || cat "${j0}" 2>/dev/null || echo ""`;let{stdout:U}=await af(X);A=U}catch(f){return z("hosts",`Cannot read hosts file, assuming entries don't exist: ${f}`,w),$.map(()=>!1)}}return $.map((Y)=>{let f=`127.0.0.1 ${Y}`,X=`::1 ${Y}`;return A.includes(f)||A.includes(X)})}kf();X$();import*as of from"node:net";function Vw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((Y)=>{let f=of.createServer(),X=setTimeout(()=>{z("port",`Checking port ${$} timed out, assuming it's in use`,A),f.close(),Y(!0)},3000);f.once("error",(U)=>{if(clearTimeout(X),U.code==="EADDRINUSE")z("port",`Port ${$} is in use`,A),Y(!0);else z("port",`Error checking port ${$}: ${U.message}`,A),Y(!0)}),f.once("listening",()=>{clearTimeout(X),z("port",`Port ${$} is available`,A),f.close(),Y(!1)});try{f.listen($,w)}catch(U){clearTimeout(X),z("port",`Exception checking port ${$}: ${U}`,A),Y(!0)}})}async function B7($,w,A,Y=50){z("port",`Finding available port starting from ${$} (max attempts: ${Y})`,A);let f=$,X=0;while(X<Y){if(X++,!await Vw(f,w,A))return z("port",`Found available port: ${f} after ${X} attempts`,A),f;z("port",`Port ${f} is in use, trying ${f+1} (attempt ${X}/${Y})`,A),f++}throw Error(`Unable to find available port after ${Y} attempts starting from ${$}`)}function CF($,w,A=5000,Y){return z("port",`Testing connection to ${w}:${$}`,Y),new Promise((f)=>{let X=of.connect({host:w,port:$,timeout:A});X.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,Y),X.end(),f(!0)}),X.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,Y),X.destroy(),f(!1)}),X.once("error",(U)=>{z("port",`Failed to connect to ${w}:${$}: ${U.message}`,Y),X.destroy(),f(!1)})})}class ef{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,A=50){this.hostname=$,this.verbose=w,this.maxRetries=A}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Vw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await CF($,this.hostname,3000,this.verbose))return z("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await B7($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await CF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){z("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var fS=new ef;$w();X$();import{spawn as E7}from"node:child_process";import*as Qw from"node:process";class $X{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||Qw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${J0(w.env)}`,A);let U=E7(Y,f,{cwd:X,env:{...Qw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),Qw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),Qw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var BS=new $X;Zf();AA();X$();var AX=new $X,T7="0.12.0",F7=new ef("0.0.0.0"),hA=new Set,ZJ=!1,wX=null,xJ=null;async function YX($){if(ZJ)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),xJ||Promise.resolve();ZJ=!0,z("cleanup","Starting cleanup process",$?.verbose),xJ=new Promise((w)=>{wX=w});try{await AX.stopAll($?.verbose),q.info("Shutting down proxy servers...");let w=[],A=Array.from(hA).map((Y)=>new Promise((f)=>{Y.close(()=>{z("cleanup","Server closed successfully",$?.verbose),f()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let Y=$.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(Y)}`,$?.verbose),Y.length>0)q.info("Cleaning up hosts file entries..."),w.push(IF(Y,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${Y.join(", ")}`,$?.verbose)}).catch((f)=>{z("cleanup",`Failed to remove hosts entries: ${f}`,$?.verbose),q.warn(`Failed to clean up hosts file entries for ${Y.join(", ")}:`,f)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),q.info("Cleaning up SSL certificates...");let Y=$.domains.map(async(f)=>{try{await mT(f,$?.verbose),z("cleanup",`Removed certificates for ${f}`,$?.verbose)}catch(X){z("cleanup",`Failed to remove certificates for ${f}: ${X}`,$?.verbose),q.warn(`Failed to clean up certificates for ${f}:`,X)}});w.push(...Y)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),q.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),q.error("Error during cleanup:",w)}finally{if(wX)wX();wX=null,ZJ=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if($$.env.NODE_ENV!=="test"&&$$.env.BUN_ENV!=="test"&&!w)$$.exit(0)}return xJ}var PJ=!1;function iJ($){if(PJ){z("signal",`Received second ${$} signal, forcing exit`,!0),$$.exit(1);return}PJ=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),YX().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),$$.exit(1)}).finally(()=>{PJ=!1})}$$.once("SIGINT",()=>iJ("SIGINT"));$$.once("SIGTERM",()=>iJ("SIGTERM"));$$.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),q.error("Uncaught exception:",$),iJ("uncaughtException")});async function HA($,w,A,Y=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${Y})`,A);let f=15000,X=Date.now();if($$.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let U=()=>new Promise((W,J)=>{let B=OF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),J(Error("Connection timed out"))}),B.once("error",(E)=>{z("connection",`Failed to connect to ${$}:${w}: ${E}`,A),B.destroy(),J(E)})});try{await U()}catch(W){if(Date.now()-X>f){z("connection",`Connection test timed out after ${f}ms, but continuing anyway`,A),q.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&Y>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${Y} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),HA($,w,A,Y-1);if(Y>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((B,E)=>{let j=_w.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(T)=>{z("connection",`Received HTTP response with status: ${T.statusCode}`,A),B()});j.on("error",(T)=>E(T)),j.on("timeout",()=>{j.destroy(),E(Error("HTTP request timed out"))}),j.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(B){return z("connection",`HTTP request to ${$}:${w} failed: ${B}`,A),z("connection",`Retrying socket connection in 2 seconds... (${Y} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),HA($,w,A,Y-1)}let J=`Failed to connect to ${$}:${w} after ${5-Y} attempts: ${W.message}`;z("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),q.warn(J),q.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function VF($){z("server",`Starting server with options: ${J0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),Y=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),f=[A.hostname];if(bJ($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await zA(f,$.verbose))[0]){q.info(`Adding ${A.hostname} to hosts file...`),q.info("This may require sudo/administrator privileges");try{await FA(f,$.verbose)}catch(W){if(q.error("Failed to add hosts entry:",W.message),q.warn("You can manually add this entry to your hosts file:"),q.warn(`127.0.0.1 ${A.hostname}`),q.warn(`::1 ${A.hostname}`),$$.platform==="win32")q.warn("On Windows:"),q.warn("1. Run notepad as administrator"),q.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else q.warn("On Unix systems:"),q.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(U){q.error("Failed to check hosts file:",U.message)}}try{await HA(w.hostname,Y,$.verbose)}catch(U){z("server",`Connection test failed: ${U}`,$.verbose),q.error(U.message),q.warn("Continuing with proxy setup despite connection test failure..."),q.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let X=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=$A({...$,to:A.hostname});if(X=await g0({...$,to:A.hostname,https:$.https}),!X){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await C1({...$,from:w.toString(),to:A.hostname,https:$.https}),X=await g0({...$,to:A.hostname,https:$.https}),!X)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(U){throw z("server",`SSL setup failed: ${U}`,$.verbose),U}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await h7({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:Y,sourceUrl:{hostname:w.hostname,host:w.host},ssl:X})}async function z7($,w,A,Y,f,X,U,W,J,B,E){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,J);function j(h){let G={};for(let[K,R]of Object.entries(h))if(!K.startsWith(":"))G[K]=R;return G}let T=(h,G)=>{z("request",`Incoming request: ${h.method} ${h.url}`,J);let K=h.url||"/",R=h.method||"GET";if(h instanceof LF.Http2ServerRequest){let S=h.headers;R=S[":method"]||R,K=S[":path"]||K}if(B){if(!K.match(/\.[a-z0-9]+$/i))if(K.endsWith("/"))K=`${K}index.html`;else K=`${K}.html`}let M=j(h.headers);if(E)M.host=`${X.hostname}:${A}`,z("request",`Changed origin: setting host header to ${M.host}`,J);let N={hostname:X.hostname,port:A,path:K,method:R,headers:M};z("request",`Proxy request options: ${J0(N)}`,J);let y=_w.request(N,(S)=>{if(z("response",`Proxy response received with status ${S.statusCode}`,J),B&&S.statusCode===404){let d$=[];if(K.endsWith(".html"))d$.push(K.slice(0,-5));else if(!K.match(/\.[a-z0-9]+$/i))d$.push(`${K}.html`);if(!K.endsWith("/"))d$.push(`${K}/index.html`);if(d$.length>0){z("cleanUrls",`Trying alternative paths: ${d$.join(", ")}`,J);let _$=(Dw)=>{if(Dw.length===0){G.writeHead(S.statusCode||404,S.headers),S.pipe(G);return}let kw=Dw[0],Zw={...N,path:kw},V1=_w.request(Zw,(r0)=>{if(r0.statusCode===200)z("cleanUrls",`Found matching path: ${kw}`,J),G.writeHead(r0.statusCode,r0.headers),r0.pipe(G);else _$(Dw.slice(1))});V1.on("error",()=>_$(Dw.slice(1))),V1.end()};_$(d$);return}}let w$={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};G.writeHead(S.statusCode||500,w$),S.pipe(G)});y.on("error",(S)=>{z("request",`Proxy request failed: ${S}`,J),q.error("Proxy request failed:",S),G.writeHead(502),G.end(`Proxy Error: ${S.message}`)}),h.pipe(y)};if(z("server",`Creating server with SSL config: ${!!U}`,J),U)return new Promise((h,G)=>{try{let K=Bun.serve({port:Y,hostname:f,tls:{key:U.key,cert:U.cert,ca:U.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let M=new URL(R.url);z("request",`Bun.serve received: ${R.method} ${M.pathname}`,J);let N=`http://${X.host}`,y=new URL(M.pathname+M.search,N);try{let S=new Headers(R.headers);if(S.set("host",X.host),E)S.set("origin",N);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",w);let w$=await fetch(y.toString(),{method:R.method,headers:S,body:R.body,redirect:"manual"}),d$=new Headers(w$.headers);if(B&&M.pathname.endsWith(".html")){let _$=M.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:_$}})}return new Response(w$.body,{status:w$.status,statusText:w$.statusText,headers:d$})}catch(S){return z("request",`Proxy error: ${S}`,J),new Response(`Proxy Error: ${S}`,{status:502})}},error(R){return z("server",`Bun.serve error: ${R}`,J),new Response(`Server Error: ${R.message}`,{status:500})}});hA.add(K),SF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!0,cleanUrls:B,verbose:J}),h()}catch(K){G(K)}});let F=_w.createServer(T);function H(h){return hA.add(h),new Promise((G,K)=>{h.listen(Y,f,()=>{z("server",`Server listening on port ${Y}`,J),SF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!!U,cleanUrls:B,verbose:J}),G()}),h.on("error",(R)=>{z("server",`Server error: ${R}`,J),K(R)})})}return H(F)}async function h7($){z("setup",`Setting up reverse proxy: ${J0($)}`,$.verbose);let{from:w,to:A,fromPort:Y,sourceUrl:f,ssl:X,verbose:U,cleanup:W,vitePluginUsage:J,changeOrigin:B,cleanUrls:E}=$,j=80,T=443,F="0.0.0.0",H=$.portManager||F7,h=bJ($);try{if(h&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await zA([A],U))[0]){q.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await FA([A],U),q.success(`Added ${A} to your hosts file.`)}catch(N){q.error(`Failed to add ${A} to your hosts file: ${N}`),q.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(h&&$$.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await zA([A],U))[0]){z("hosts",`${A} not found in hosts file, adding...`,U);try{await FA([A],U)}catch(N){z("hosts",`Failed to add ${A} to hosts file: ${N}`,U)}}}if(X&&!H.usedPorts.has(j)){if(!await Vw(j,F,U))z("setup","Starting HTTP redirect server",U),QF(U),H.usedPorts.add(j);else if(z("setup","Port 80 is in use, skipping HTTP redirect",U),U)q.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let G=X?T:j,K=await Vw(G,F,U),R;if(K){if(z("setup",`Port ${G} is already in use`,U),U)q.warn(`Port ${G} is already in use. This may be another instance of rpx or another service.`);if(G===443){if(R=await H.getNextAvailablePort(3443,!0),z("setup",`Using port ${R} instead of ${G}`,U),U)q.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await H.getNextAvailablePort(G+1000,!0),z("setup",`Using port ${R} instead of ${G}`,U),U)q.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=G,H.usedPorts.add(R),z("setup",`Using standard ${G===443?"HTTPS":"HTTP"} port ${G} for ${A}`,U);await z7(w,A,Y,R,F,f,X,J,U,E,B)}catch(G){z("setup",`Setup failed: ${G}`,U),q.error(`Failed to setup reverse proxy: ${G.message}`),YX({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:J})}}function QF($){z("redirect","Starting HTTP redirect server",$);let w=_w.createServer((A,Y)=>{let f=A.headers.host||"";z("redirect",`Redirecting request from ${f}${A.url} to HTTPS`,$),Y.writeHead(301,{Location:`https://${f}${A.url}`}),Y.end()}).listen(80);hA.add(w),z("redirect","HTTP redirect server started",$)}function _F($){let w={...jU,...$};if(z("proxy",`Starting proxy with options: ${J0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){q.error("viaDaemon mode requires both `from` and `to`");return}_J({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((J)=>{q.error(`Failed to register with rpx daemon: ${J.message}`),$$.exit(1)});return}let A=w.to||"",Y=A.split(".").pop()?.toLowerCase()||"",f=$$.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),X=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(f&&X.includes(Y)&&w?.verbose)q.warn(`The .${Y} TLD may not work reliably for local development`),q.info(` Google owns .${Y} with HSTS preloading, which can bypass local DNS`),q.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)Promise.resolve().then(() => (S1(),gf)).then(({setupDevelopmentDns:J})=>{J({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(Y))q.success(`DNS server started for .${Y} domains`);else q.success(`DNS server started for .${Y} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((J)=>{z("dns",`Failed to start DNS server: ${J}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:$A(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${J0(W)}`,w.verbose),VF(W).catch((J)=>{z("proxy",`Failed to start proxy: ${J}`,w.verbose),q.error(`Failed to start proxy: ${J.message}`),YX({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function H7($){return $?.verbose||!1}function bJ($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function DF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=H7(w),Y=bJ(w);if(z("config",`Starting with config: ${J0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),z("config",`Hosts management enabled? ${Y}`,A),w.viaDaemon){let h="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((G)=>({id:G.id,from:G.from,to:G.to,cleanUrls:G.cleanUrls??w.cleanUrls,changeOrigin:G.changeOrigin??w.changeOrigin,pathRewrites:G.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await _J({proxies:h,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let H of w.proxies)if(H.start){let h=`${H.from}-${H.to}`;try{z("watch",`Starting command for ${h} with command: ${H.start.command}`,A),q.info(`Starting command for ${h}...`),await AX.startProcess(h,H.start,A);let G=new URL(H.from.startsWith("http")?H.from:`http://${H.from}`),K=G.hostname||"localhost",R=Number(G.port)||80;try{await HA(K,R,A),z("watch",`Dev server is ready at ${K}:${R}`,A)}catch(M){z("watch",`Connection check failed, but continuing with proxy setup: ${M}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(G){throw z("watch",`Failed to start command for ${h}: ${G}`,A),Error(`Failed to start command for ${h}: ${G}`)}}else z("watch",`No start command for proxy ${H.from} -> ${H.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let H=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await AX.startProcess(H,w.start,A);let h=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),G=h.hostname||"localhost",K=Number(h.port)||80;try{await HA(G,K,A),z("watch",`Dev server is ready at ${G}:${K}`,A)}catch(R){z("watch",`Connection check failed, but continuing with proxy setup: ${R}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(h){throw z("watch",`Failed to run start command: ${h}`,A),Error(`Failed to run start command: ${h}`)}}else z("watch","No start command found in config",A);let f="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if($$.platform!=="win32"&&(w.https||Y)){if(!Nw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),j7("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let H=await g0(w);if(!H){if(z("ssl",`No valid or trusted certificates found for ${f}, generating new ones`,w.verbose),await C1(w),H=await g0(w),!H)throw Error(`Failed to load SSL certificates after generation for ${f}`)}else z("ssl",`Using existing and trusted certificates for ${f}`,w.verbose);w._cachedSSLConfig=H}let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],U=X.map((H)=>H.to||"rpx.localhost"),W=w._cachedSSLConfig,J=U.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],j=[...new Set(J.map((H)=>H.split(".").pop()?.toLowerCase()))],T=j.filter((H)=>!!H&&B.includes(H));if(T.length>0&&A)q.warn(`The following TLDs may not work reliably for local development: ${T.map((H)=>`.${H}`).join(", ")}`),q.info(" These TLDs have HSTS preloading which can bypass local DNS"),q.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Y&&$$.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (S1(),gf));if(await H({domains:J,verbose:A})){if(A)if(j.every((K)=>!!K&&E.includes(K)))q.success(`DNS server started for ${j.map((K)=>`.${K}`).join(", ")} domains`);else q.success(`DNS server started for ${j.map((K)=>`.${K}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let F=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (S1(),gf));await H({verbose:w.verbose})}catch(H){z("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await AX.stopAll(w.verbose)}catch(H){z("cleanup",`Error stopping processes: ${H}`,w.verbose)}await YX({domains:U,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if($$.on("SIGINT",F),$$.on("SIGTERM",F),$$.on("uncaughtException",(H)=>{z("process",`Uncaught exception: ${H}`,!0),console.error("Uncaught exception:",H),F()}),W&&X.length>1){z("proxies",`Creating shared HTTPS server for ${X.length} domains`,A);let H=new Map;for(let N of X){let y=N.to||"rpx.localhost",S=N.cleanUrls||!1;if(N.static)H.set(y,{static:wA(N.static,S),cleanUrls:S}),z("proxies",`Route: ${y} → static ${typeof N.static==="string"?N.static:N.static.dir}`,A);else{let w$=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);H.set(y,{sourceHost:w$.host,cleanUrls:S,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites}),z("proxies",`Route: ${y} → ${w$.host}`,A)}if(Y&&!xf(y)&&!y.includes("localhost")&&!y.includes("127.0.0.1"))try{if(!(await zA([y],A))[0])await FA([y],A)}catch{z("hosts",`Could not add hosts entry for ${y}`,A)}}if(!await Vw(80,"0.0.0.0",A))QF(A);let G=443;if(await Vw(G,"0.0.0.0",A)){if(z("proxies",`Port ${G} is already in use, cannot start shared proxy`,A),A)q.warn(`Port ${G} is in use. Shared HTTPS proxy cannot start.`);return}let R=YA((N)=>XA(H,N),A),M=fA(A);try{let N=Bun.serve({port:G,hostname:"0.0.0.0",tls:{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1},fetch(y,S){return R(y,S)},websocket:M,error(y){return z("server",`Shared proxy server error: ${y}`,A),new Response(`Server Error: ${y.message}`,{status:500})}});hA.add(N),z("proxies",`Shared HTTPS proxy listening on port ${G} for ${H.size} domains`,A)}catch(N){z("proxies",`Failed to start shared proxy: ${N}`,A),console.error("Failed to start shared HTTPS proxy:",N),F()}}else for(let H of X)try{let h=H.to||"rpx.localhost";z("proxy",`Starting proxy for ${h} with SSL config: ${!!W}`,H.verbose),await VF({from:H.from||"localhost:5173",to:h,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:W,changeOrigin:H.changeOrigin||!1})}catch(h){z("proxies",`Failed to start proxy for ${H.to}: ${h}`,H.verbose),console.error(`Failed to start proxy for ${H.to}:`,h),F()}}function SF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${y0.green(y0.bold("rpx"))} ${y0.green(`v${T7}`)}`),console.log(` ${y0.green("➜")} ${y0.dim($?.from??"")} ${y0.dim("➜")} ${y0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${y0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${y0.green("➜")} Clean URLs enabled`)}aU();var VS=new qw("rpx",{showTags:!1});function kF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}m$.chdir(K7(G7(R7(import.meta.url)),".."));var t$=new TX("rpx"),ZF="0.12.0";t$.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return DF(pw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(Y){console.error("Failed to parse start-env JSON:",Y),m$.exit(1)}w.start=A}return _F(w)});t$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=kF(pw)?pw.proxies.find((Y)=>Y.to===$||`${Y.from}-${Y.to}`===$):pw.to===$?pw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),m$.exit(1);try{await pf.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(Y){console.error(`Failed to start dev server for ${$}:`,Y),m$.exit(1)}});t$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await pf.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),m$.exit(1)}});t$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await pf.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),m$.exit(1)}});t$.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("--verbose","Enable verbose logging").action(async($)=>{try{await(await jF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,verbose:$.verbose??!0})).done,m$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),m$.exit(1)}});t$.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await FF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});t$.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??E0(),A=await Fw(w),Y=await tf(w),f=$.registryDir,X=await RF(f).catch(()=>[]);if($.json){console.log(JSON.stringify({running:Y,pid:A,pidFile:zw(w),rpxDir:w,registryDir:f??Lw(),entries:X},null,2));return}if(!Y){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${zw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${zw(w)}`);if(console.log(`registry: ${f??Lw()}`),X.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${X.length}):`);for(let U of X){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});t$.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),m$.exit(1);if(!O1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),m$.exit(1);try{await GF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),m$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await TF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),m$.exit(1)}});t$.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(!O1($))console.error(`invalid id: ${JSON.stringify($)}`),m$.exit(1);let A=await QJ($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await KF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t$.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??E0();if(await tf(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await zF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});t$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(ZF)});t$.version(ZF);t$.help();t$.run();
|