@stacksjs/rpx 0.11.13 → 0.11.14
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 +152 -152
- package/dist/{chunk-zs1tyy8z.js → chunk-3pgh05pc.js} +1 -1
- package/dist/chunk-5ygwd93k.js +1 -0
- package/dist/{chunk-747af2w4.js → chunk-a0ddh9cv.js} +1 -1
- package/dist/chunk-tx5hnj92.js +157 -0
- package/dist/daemon-runner.d.ts +3 -2
- package/dist/daemon.d.ts +2 -1
- package/dist/host-match.d.ts +23 -0
- package/dist/index.d.ts +13 -2
- package/dist/index.js +4 -4
- 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 +33 -1
- package/package.json +1 -1
- package/src/daemon-runner.ts +12 -4
- package/src/daemon.ts +54 -12
- package/src/host-match.ts +52 -0
- package/src/index.ts +16 -2
- 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 +79 -1
- package/dist/chunk-kbnzcycw.js +0 -1
- package/dist/chunk-pncxrxde.js +0 -157
package/dist/bin/cli.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
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
|
-
`,
|
|
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 T of
|
|
14
|
-
`;if(
|
|
15
|
-
`;if(
|
|
16
|
-
`);if(this[
|
|
17
|
-
`,
|
|
18
|
-
`),
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
4
|
+
import{createRequire as o9}from"node:module";var r9=Object.defineProperty;var a9=($)=>$;function s9($,w){this[$]=a9.bind(null,w)}var TW=($,w)=>{for(var A in w)r9($,A,{get:w[A],enumerable:!0,configurable:!0,set:s9.bind(w,A)})};var h$=($,w)=>()=>($&&(w=$($=0)),w);var u=o9(import.meta.url);import{existsSync as _W,statSync as DW}from"fs";import{existsSync as Jf,mkdirSync as FK,readdirSync as zK,readFileSync as Yf,writeFileSync as fK}from"fs";import{homedir as Sw}from"os";import{dirname as HK,resolve as s$}from"path";import tA from"process";import{existsSync as QW,statSync as kW}from"fs";import{existsSync as KU,mkdirSync as Uf,readdirSync as Zf,writeFileSync as Wf}from"fs";import{homedir as Ow}from"os";import{dirname as xW,resolve as D$}from"path";import fw from"process";import{join as Bf,relative as Ef,resolve as PW}from"path";import xA from"process";import{existsSync as hB,mkdirSync as yK,readdirSync as VK,writeFileSync as SK}from"fs";import{homedir as eY}from"os";import{dirname as _K,resolve as _$}from"path";import V1 from"process";import{join as jf,relative as Ff,resolve as bW}from"path";import PA from"process";import{existsSync as RB,mkdirSync as PK,readdirSync as bK,writeFileSync as iK}from"fs";import{dirname as cK,resolve as bA}from"path";import hU from"process";import{Buffer as a0}from"buffer";import{createCipheriv as zf,createDecipheriv as ff,randomBytes as $U}from"crypto";import{closeSync as wU,createReadStream as iW,createWriteStream as Gf,existsSync as AU,fsyncSync as uW,openSync as cW,writeFileSync as Tf}from"fs";import{access as Hf,constants as vW,mkdir as qf,readdir as TA,rename as mW,stat as Xw,unlink as HA,writeFile as JU}from"fs/promises";import{join as _w}from"path";import R$ from"process";import{pipeline as Kf}from"stream/promises";import{createGzip as nW}from"zlib";import Dw from"process";import V0 from"process";import{Buffer as C0}from"buffer";import{createCipheriv as hf,createDecipheriv as Rf,randomBytes as YU}from"crypto";import{closeSync as UU,createReadStream as dW,createWriteStream as Nf,existsSync as qA,fsyncSync as gW,openSync as lW,writeFileSync as Mf}from"fs";import{access as If,constants as pW,mkdir as Cf,readdir as KA,rename as tW,stat as Qw,unlink as hA,writeFile as ZU}from"fs/promises";import{isAbsolute as Lf,join as kw,resolve as yf}from"path";import S from"process";import{pipeline as Vf}from"stream/promises";import{createGzip as rW}from"zlib";import xw from"process";import S0 from"process";import RA from"process";import{existsSync as NA}from"fs";import{resolve as WU}from"path";import{existsSync as Sf}from"fs";import{existsSync as Of,readdirSync as Xf}from"fs";import{extname as BU,resolve as aW}from"path";import _f from"process";import{join as Df,relative as Qf,resolve as sW}from"path";import iA from"process";import{Buffer as L0}from"buffer";import{createCipheriv as kf,createDecipheriv as xf,randomBytes as EU}from"crypto";import{closeSync as jU,createReadStream as oW,createWriteStream as Pf,existsSync as MA,fsyncSync as eW,openSync as $B,writeFileSync as bf}from"fs";import{access as uf,constants as wB,mkdir as cf,readdir as IA,rename as AB,stat as Pw,unlink as CA,writeFile as FU}from"fs/promises";import{isAbsolute as vf,join as bw,resolve as mf}from"path";import O from"process";import{pipeline as nf}from"stream/promises";import{createGzip as JB}from"zlib";import iw from"process";import O0 from"process";import yA from"process";import{existsSync as VA}from"fs";import{resolve as qU}from"path";import{existsSync as E2}from"fs";class qB{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 Y=this.generateKey($,A),U=J??this.options.ttl,Z=this.estimateSize(w);this.cache.set(Y,{value:w,timestamp:new Date,ttl:U,hits:0,size:Z}),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(!_W($))return!0;return DW($).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 Y=_W(A)?DW(A):null,U=Y?Y.mtime:new Date;this.set($,{value:w,fileTimestamp:U},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,Y)=>J+Y.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 KB{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),Y=new Date;try{let U=await w(),Z=performance.now()-J;return this.recordMetric({operation:$,duration:Z,timestamp:Y,...A}),U}catch(U){let Z=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Z,timestamp:Y,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((Y)=>Y.duration),J=A.reduce((Y,U)=>Y+U,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 lf($,w){this[$]=gf.bind(null,w)}class _U{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let 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 Y=this.generateKey($,A),U=J??this.options.ttl,Z=this.estimateSize(w);this.cache.set(Y,{value:w,timestamp:new Date,ttl:U,hits:0,size:Z}),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(!QW($))return!0;return kW($).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 Y=QW(A)?kW(A):null,U=Y?Y.mtime:new Date;this.set($,{value:w,fileTimestamp:U},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,Y)=>J+Y.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 DU{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),Y=new Date;try{let U=await w(),Z=performance.now()-J;return this.recordMetric({operation:$,duration:Z,timestamp:Y,...A}),U}catch(U){let Z=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Z,timestamp:Y,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((Y)=>Y.duration),J=A.reduce((Y,U)=>Y+U,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 rf($,w={}){let J=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return J?`${$}:${J}`:$}function af($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function sf($){return $.getStats().size*2}function QU($,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 Y of $)if(r(Y)&&"name"in Y){if(!J.find((Z)=>r(Z)&&("name"in Z)&&Z.name===Y.name))J.push(Y)}else if(r(Y)&&"path"in Y){if(!J.find((Z)=>r(Z)&&("path"in Z)&&Z.path===Y.path))J.push(Y)}else if(!J.some((U)=>uA(U,Y)))J.push(Y);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);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 Y=w[J];if(Y===null||Y===void 0)continue;else if(r(Y)&&r(A[J]))A[J]=QU(A[J],Y);else if(Array.isArray(Y)&&Array.isArray(A[J]))if(Y.length>0&&A[J].length>0&&r(Y[0])&&r(A[J][0])){let U=[...Y];for(let Z of A[J])if(r(Z)&&"name"in Z){if(!U.find((W)=>r(W)&&("name"in W)&&W.name===Z.name))U.push(Z)}else if(r(Z)&&"path"in Z){if(!U.find((W)=>r(W)&&("path"in W)&&W.path===Z.path))U.push(Z)}else if(!U.some((B)=>uA(B,Z)))U.push(Z);A[J]=U}else if(Y.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...Y];for(let Z of A[J])if(!U.includes(Z))U.push(Z);A[J]=U}else A[J]=Y;else A[J]=Y}return A}function uA($,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(!uA($[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 Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!uA($[Y],w[Y]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function of($,w){if(!RB($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return QU(w,J)}catch{return null}}catch{return null}}async function ef({name:$="",cwd:w,defaultConfig:A}){let J=w||hU.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Z of U)for(let B of Y){let W=bA(J,`${Z}${B}`),E=await of(W,A);if(E!==null)return E}try{let Z=bA(J,"package.json");if(RB(Z)){let W=(await import(Z))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return QU(A,W)}catch{}}}catch{}return A}function $G($,w={}){let A=PA.cwd();while(A.includes("storage"))A=bW(A,"..");let J=bW(A,$||"");if(w?.relative)return Ff(PA.cwd(),J);return J}async function wG(){try{let $=await ef({name:"clarity",defaultConfig:XA,cwd:PA.cwd(),endpoint:"",headers:{}});return{...XA,...$}}catch{return XA}}function $$(){if(V0.env.NODE_ENV==="test"||V0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function AG(){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 MB{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: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 cA{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={...NU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new MB,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??R$.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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{..._A,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{..._A};return{..._A,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:NU.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 Y,U=0,Z=3,B=1000;while(U<Z)try{try{try{await Hf(this.config.logDirectory,vW.F_OK|vW.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await qf(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:a0.from($);try{if(!AU(this.currentLogFile))await JU(this.currentLogFile,"",{mode:420});if(Y=cW(this.currentLogFile,"a",420),Tf(Y,W,{flag:"a"}),uW(Y),Y!==void 0)wU(Y),Y=void 0;if((await Xw(this.currentLogFile)).size===0){if(await JU(this.currentLogFile,W,{flag:"w",mode:420}),(await Xw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let j=E;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<Z-1){let F=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,F);let f=B*2**U;await new Promise((z)=>setTimeout(z,f)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{wU(Y)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(W){if(U===Z-1){let j=W,F=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),W}U++;let E=B*2**(U-1);await new Promise((j)=>setTimeout(j,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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($$())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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Z=Math.max(1,U);if(Y.length>Z)for(let[B]of Y.slice(Z))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return $U(16).toString("hex")}generateKey(){return $U(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=$U(16),J=zf("aes-256-gcm",w,A),Y=a0.concat([J.update($,"utf8"),J.final()]),U=J.getAuthTag();return{encrypted:a0.concat([A,Y,U]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=nW(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(a0.from(a0.concat(Y)))),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 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 Y=await TA(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await Xw(A).catch(()=>null))try{if(await mW(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await HA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await JU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await Xw(A).catch(()=>null))await mW(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await TA(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,B)=>B.localeCompare(Z));for(let Z of U.slice(w.maxFiles))await HA(_w(this.config.logDirectory,Z))}}}async compressLogFile($,w){let A=iW($),J=Gf(w),Y=nW();await Kf(A,Y,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()})),AU(this.currentLogFile))try{let $=cW(this.currentLogFile,"r+");uW($),wU($)}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 TA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await HA(_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.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=R$.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${g.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}async log($,w,...A){let J=new Date,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);if(this.fancy&&!$$()){let E=DB[$],j=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:g.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:g.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.error(F),B){let f=B.split(`
|
|
5
|
+
`);for(let z of f)if(z.trim()&&!z.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:g.gray(` ${z}`),level:$,showTimestamp:!1}))}break}}else if(!$$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${U} ${this.environment}.${$.toUpperCase()}: ${Z}
|
|
6
|
+
`;if(B)W+=`${B}
|
|
7
|
+
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!$$()){let A=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:g.blue("◐"),tag:A,message:`${g.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
8
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!$$()){let j=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:g.green("✓"),tag:j,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!$$())console.error(E.trim());await this.writeToFile(E)}}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 cA(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($$())throw Error("createReadStream is not supported in browser environments");if(!AU(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 J=a0.isBuffer($)?$:a0.from($,"base64"),Y=J.slice(0,16),U=J.slice(-16),Z=J.slice(16,-16),B=ff("aes-256-gcm",A,Y);return B.setAuthTag(U),a0.concat([B.update(Z),B.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 $$()}isServerMode(){return!$$()}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&&!$$()){let U=$.split(`
|
|
9
|
+
`),Z=Math.max(...U.map((j)=>j.length))+2,B=`┌${"─".repeat(Z)}┐`,W=`└${"─".repeat(Z)}┘`,E=U.map((j)=>{let F=" ".repeat(Z-j.length-2);return`│ ${j}${F} │`});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(B)})),E.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(W),showTimestamp:!1}))}else if(!$$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt($){if($$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.toString().trim().toLowerCase();R$.stdin.removeListener("data",A);try{if(typeof R$.stdin.setRawMode==="function")R$.stdin.setRawMode(!1)}catch{}R$.stdin.pause(),console.error(""),w(Y==="y"||Y==="yes")};try{if(typeof R$.stdin.setRawMode==="function")R$.stdin.setRawMode(!0)}catch{}R$.stdin.resume(),R$.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 Z=/%([sdijfo%])/g,B=0;if(A=$.replace(Z,(W,E)=>{if(E==="%")return"%";if(B>=w.length)return W;let j=w[B++];switch(E){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 W}}),B<w.length)A+=` ${w.slice(B).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!$$()){let Z=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",B=g.blue("◐");console.error(`${B} ${Z} ${g.cyan(A)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}progress($,w=""){if(!this.enabled||!this.fancy||$$()||$<=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:(Z,B)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Z)),B!==void 0)this.activeProgressBar.message=B;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Z!==void 0)this.activeProgressBar.message=Z;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Z,B="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;R$.stdout.write(`${"\r".padEnd(R$.stdout.columns||80)}\r`),this.log(B,Z),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||$$()||!R$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=g.green("━".repeat(J)),Z=g.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=w||A===100?g.green("✓"):g.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=R$.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,R$.stdout.write($.lastRenderedLine),w)R$.stdout.write(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!R$.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 TA(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=_w(this.config.logDirectory,J);if($.before)try{if((await Xw(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);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 HA(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function OA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&c(w[0])&&"id"in w[0]&&w[0].id===3&&c(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(c(w)&&c($)&&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(c($)&&"arr"in $&&Array.isArray($.arr)&&c(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&c(w[0])&&c($[0])){let J=[...w];for(let Y of $)if(c(Y)&&"name"in Y){if(!J.find((Z)=>c(Z)&&("name"in Z)&&Z.name===Y.name))J.push(Y)}else if(c(Y)&&"path"in Y){if(!J.find((Z)=>c(Z)&&("path"in Z)&&Z.path===Y.path))J.push(Y)}else if(!J.some((U)=>vA(U,Y)))J.push(Y);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}if(!c(w)||!c($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let Y=w[J];if(Y===null||Y===void 0)continue;else if(c(Y)&&c(A[J]))A[J]=OA(A[J],Y);else if(Array.isArray(Y)&&Array.isArray(A[J]))if(Y.length>0&&A[J].length>0&&c(Y[0])&&c(A[J][0])){let U=[...Y];for(let Z of A[J])if(c(Z)&&"name"in Z){if(!U.find((W)=>c(W)&&("name"in W)&&W.name===Z.name))U.push(Z)}else if(c(Z)&&"path"in Z){if(!U.find((W)=>c(W)&&("path"in W)&&W.path===Z.path))U.push(Z)}else if(!U.some((B)=>vA(B,Z)))U.push(Z);A[J]=U}else if(Y.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...Y];for(let Z of A[J])if(!U.includes(Z))U.push(Z);A[J]=U}else A[J]=Y;else A[J]=Y}return A}function kU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:OA($,w);if(Array.isArray($))return A==="replace"?w:OA($,w);if(!c(w)||!c($))return w;let J={...$};for(let Y of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,Y))continue;let U=w[Y],Z=J[Y];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Z))if(A==="replace")J[Y]=U;else J[Y]=OA(Z,U);else if(c(U)&&c(Z))J[Y]=kU(Z,U,A);else J[Y]=U}return J}function vA($,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(!vA($[A],w[A]))return!1;return!0}if(c($)&&c(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!vA($[Y],w[Y]))return!1}return!0}return!1}function c($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function LA($,w,A="replace"){if(!hB($))return null;try{let J=await import($),Y=J.default||J;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return kU(w,Y,A)}catch{return null}}catch{return null}}function JG($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),Y={...w};function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${J}_${F.map(f).join("_")}`,H=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)M$.info(`Checking environment variable ${z} for config ${$}.${F.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))W[E]=U(j,F);else{let T=V1.env[z]||V1.env[H];if(T!==void 0){if(A)M$.info(`Using environment variable ${T?z:H} for config ${$}.${F.join(".")}`);if(typeof j==="number")W[E]=Number(T);else if(typeof j==="boolean")W[E]=T.toLowerCase()==="true";else if(Array.isArray(j))try{let q=JSON.parse(T);if(Array.isArray(q))W[E]=q;else W[E]=T.split(",").map((K)=>K.trim())}catch{W[E]=T.split(",").map((q)=>q.trim())}else W[E]=T}}}return W}return U(Y)}async function YG({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:Y,verbose:U=!1,checkEnv:Z=!0,arrayStrategy:B="replace"}){let W=Z&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?JG($,Y,U):Y,E=A||V1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(U)M$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),f=[`${$}.config`,`.${$}.config`].filter(Boolean),z=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([E,_$(E,"config"),_$(E,".config"),J?_$(E,J):void 0].filter(Boolean)));for(let q of T){if(U)M$.info(`Searching for configuration in: ${q}`);let h=[_$(E,"config"),_$(E,".config")].concat(J?[_$(E,J)]:[]).includes(q)?[...F,...f,...z,...H]:[...f,...F,...H,...z];for(let I of h)for(let N of j){let M=_$(q,`${I}${N}`),V=await LA(M,W,B);if(V!==null){if(U)M$.success(`Configuration loaded from: ${M}`);return V}}}if($){let q=_$(eY(),".config",$),K=["config",`${$}.config`];if(w)K.push(`${w}.config`);if(U)M$.info(`Checking user config directory: ${q}`);for(let h of K)for(let I of j){let N=_$(q,`${h}${I}`),M=await LA(N,W,B);if(M!==null){if(U)M$.success(`Configuration loaded from user config directory: ${N}`);return M}}}if($){let q=_$(eY(),".config"),K=[`.${$}.config`];if(w)K.push(`.${w}.config`);if(U)M$.info(`Checking user config directory for dotfile configs: ${q}`);for(let h of K)for(let I of j){let N=_$(q,`${h}${I}`),M=await LA(N,W,B);if(M!==null){if(U)M$.success(`Configuration loaded from user config directory dotfile: ${N}`);return M}}}if($){let q=eY(),K=[`.${$}.config`,`.${$}`];if(w)K.push(`.${w}.config`),K.push(`.${w}`);if(U)M$.info(`Checking user home directory for dotfile configs: ${q}`);for(let h of K)for(let I of j){let N=_$(q,`${h}${I}`),M=await LA(N,W,B);if(M!==null){if(U)M$.success(`Configuration loaded from user home directory: ${N}`);return M}}}try{let q=_$(E,"package.json");if(hB(q)){let K=await import(q),h=K[$];if(!h&&w){if(h=K[w],h&&U)M$.success(`Using alias "${w}" configuration from package.json`)}if(h&&typeof h==="object"&&!Array.isArray(h))try{if(U)M$.success(`Configuration loaded from package.json: ${h===K[$]?$:w}`);return kU(W,h,B)}catch(I){if(U)M$.warn("Failed to merge package.json config:",I)}}}catch(q){if(U)M$.warn("Failed to load package.json:",q)}if(U)M$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function UG($,w={}){let A=xA.cwd();while(A.includes("storage"))A=PW(A,"..");let J=PW(A,$||"");if(w?.relative)return Ef(xA.cwd(),J);return J}async function ZG(){try{let $=await YG({name:"clarity",alias:"logging",defaultConfig:DA,cwd:xA.cwd()});return{...DA,...$||{}}}catch{return DA}}function Z$(){if(S0.env.NODE_ENV==="test"||S0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function WG(){if(S0.env.NODE_ENV==="test"||S0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof S0<"u"){let $=S0.type;if($==="renderer"||$==="worker")return!1;return!!(S0.versions&&(S0.versions.node||S0.versions.bun))}return!1}class IB{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: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={...MU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new IB,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??S.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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,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{...QA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...QA};return{...QA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:MU.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!Z$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let Y,U=0,Z=3,B=1000;while(U<Z)try{try{try{await If(this.config.logDirectory,pW.F_OK|pW.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Cf(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:C0.from($);try{if(!qA(this.currentLogFile))await ZU(this.currentLogFile,"",{mode:420});if(Y=lW(this.currentLogFile,"a",420),Mf(Y,W,{flag:"a"}),gW(Y),Y!==void 0)UU(Y),Y=void 0;if((await Qw(this.currentLogFile)).size===0){if(await ZU(this.currentLogFile,W,{flag:"w",mode:420}),(await Qw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let j=E;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<Z-1){let F=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,F);let f=B*2**U;await new Promise((z)=>setTimeout(z,f)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{UU(Y)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(W){if(U===Z-1){let j=W,F=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),W}U++;let E=B*2**(U-1);await new Promise((j)=>setTimeout(j,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 kw(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 kw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return kw(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,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Z=Math.max(1,U);if(Y.length>Z)for(let[B]of Y.slice(Z))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return YU(16).toString("hex")}generateKey(){return YU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=YU(16),J=hf("aes-256-gcm",w,A),Y=C0.isBuffer($)?$:C0.from($,"utf8"),U=J.update(Y),Z=J.final(),B=U.length+Z.length,W=J.getAuthTag(),E=C0.allocUnsafe(16+B+16);return A.copy(E,0),U.copy(E,16),Z.copy(E,16+U.length),W.copy(E,16+B),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=rW(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(C0.from(C0.concat(Y)))),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(Z$())return;if(!this.shouldWriteToFile())return;let $=await Qw(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 Y=await KA(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await Qw(A).catch(()=>null))try{if(await tW(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await hA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await ZU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await Qw(A).catch(()=>null))await tW(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await KA(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,B)=>B.localeCompare(Z));for(let Z of U.slice(w.maxFiles))await hA(kw(this.config.logDirectory,Z))}}}async compressLogFile($,w){let A=dW($),J=Nf(w),Y=rW();await Vf(A,Y,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()})),qA(this.currentLogFile))try{let $=lW(this.currentLogFile,"r+");gW($),UU($)}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 KA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await hA(kw(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||Z$())return!1;let $=typeof S.env.NO_COLOR<"u",w=S.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=S.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${D.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,Y)=>{let U=D.underline(D.blue(J)),Z=this.toAbsoluteFilePath(Y);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(Z)}`,W="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${B}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),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(Z$())return!1;let $=S.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=S.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Lf(w)||w.startsWith("./")||w.startsWith("../"))w=yf(w);else return null;return qA(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,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);let{consoleText:W,fileText:E}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":QB[$],f=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:D.gray(W),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:D.green(W),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.error(z),B){let H=B.split(`
|
|
13
|
+
`);for(let T of H)if(T.trim()&&!T.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:D.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!Z$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}if(!this.shouldLog($))return;let j=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
14
|
+
`;if(B)j+=`${B}
|
|
15
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!Z$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!Z$()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!Z$()&&S.stdout.isTTY)S.stdout.write(`
|
|
16
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!Z$()&&S.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)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":D.blue("◐"),tag:A,message:`${D.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
17
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":D.green("✓"),tag:j,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!Z$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}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 mA(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(!qA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let J=C0.isBuffer($)?$:C0.from($,"base64"),Y=J.subarray(0,16),U=J.subarray(J.length-16),Z=J.subarray(16,J.length-16),B=Rf("aes-256-gcm",A,Y);B.setAuthTag(U);let W=B.update(Z),E=B.final(),j=W.length+E.length,F=C0.allocUnsafe(j);return W.copy(F,0),E.copy(F,W.length),F.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 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),J=this.formatFileTimestamp(w),{consoleText:Y,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=Y.split(`
|
|
18
|
+
`),W=Math.max(...B.map((f)=>f.length))+2,E=`┌${"─".repeat(W)}┐`,j=`└${"─".repeat(W)}┘`,F=B.map((f)=>{return this.formatConsoleMessage({timestamp:A,message:D.cyan(f),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:D.cyan(E),showTimestamp:!1})),F.forEach((f)=>console.error(f)),console.error(this.formatConsoleMessage({timestamp:A,message:D.cyan(j),showTimestamp:!1}))}else if(!Z$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${J} ${this.environment}.INFO: [BOX] ${U}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(Z$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${D.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.toString().trim().toLowerCase();S.stdin.removeListener("data",A);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),w(Y==="y"||Y==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.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 W=/%([sdijfo%])/g,E=0;if(A=$.replace(W,(j,F)=>{if(F==="%")return"%";if(E>=w.length)return j;let f=w[E++];switch(F){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return j}}),E<w.length)A+=` ${w.slice(E).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:J,fileText:Y}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${D.blue("◐")} `;console.error(`${E}${W} ${D.cyan(J)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!S.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=D.green("━".repeat(J)),Z=D.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?D.green("✓"):D.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${D.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=S.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,S.stdout.write($.lastRenderedLine),w)S.stdout.write(`
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Z$()||!S.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 KA(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=kw(this.config.logDirectory,J);if($.before)try{if((await Qw(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);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 hA(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function CB($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:Y=()=>!0,fallback:U}=w,Z=Error("Unknown error occurred");for(let B=0;B<=A;B++)try{return await $()}catch(W){if(Z=W instanceof Error?W:Error(String(W)),B===A||!Y(Z))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}function LB($){return $ instanceof l$}function BG($){return $ instanceof nA}function EG($){if(LB($))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 rA{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:J,useCamelCase:Y=!0,useBackwardCompatibility:U=!0,customParsers:Z={},verbose:B=!1,trackPerformance:W=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],j,{useCamelCase:Y,useBackwardCompatibility:U,customParsers:Z,verbose:B,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return X1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=Z.map((j)=>this.formatEnvKey(j,J.useCamelCase)),W=`${A}_${B.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Z.map((j)=>j.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Z,A,J);else{let j=RA.env[W]||(E?RA.env[E]:void 0);if(j!==void 0){if(J.verbose){let F=RA.env[W]?W:E}try{$[Y]=this.parseEnvironmentValue(j,typeof U,W,J.customParsers,J.configName)}catch(F){if(F instanceof dA)throw F;throw s0.envVar(W,j,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,Y){for(let[U,Z]of Object.entries(J))try{return Z($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw s0.envVar(A,$,`${w} (via ${U.name} parser)`,Y)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,Y]of Object.entries(RA.env))if(J.startsWith(A)&&Y!==void 0)w[J]=Y;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(Y){J.push(`Cannot parse value "${w}" as ${A}: ${Y}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:Y="text"}=A,U=J||this.generateEnvPrefix($),Z=[];switch(this.extractEnvVarInfo(w,[],U,Z),Y){case"markdown":return this.formatAsMarkdown(Z,$);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,$)}}extractEnvVarInfo($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=`${A}_${Z.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Z,A,J);else J.push({key:B,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Z.join(".")}`,example:this.generateExample(U)})}}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
22
|
|
|
23
23
|
`;for(let J of $)A+=`${J.key}
|
|
24
24
|
`,A+=` Type: ${J.type}
|
|
@@ -30,25 +30,25 @@ import{createRequire as uj}from"node:module";var bj=Object.defineProperty;var ij
|
|
|
30
30
|
`;A+=`| Variable | Type | Description | Example |
|
|
31
31
|
`,A+=`|----------|------|-------------|----------|
|
|
32
32
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
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
|
-
${
|
|
33
|
+
`;return A}}function jG($,w){let A=XB("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function yB($,w,A={}){return VB($,w,A,new WeakMap)}function VB($,w,A,J){let{arrayMergeMode:Y="replace",skipNullish:U=!1,customMerger:Z}=A;if(w===null||w===void 0)return U?$:w;if(Z){let B=Z($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return SB($,w,Y,J);if(!o$(w)||!o$($))return w;return GG($,w,A,J)}function SB($,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 FG($,w);case"smart":return zG($,w,J);default:return w}return w}function FG($,w){let A=[...w];for(let J of $)if(!A.some((Y)=>RU(Y,J)))A.push(J);return A}function zG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return fG($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}function fG($,w,A){let J=[...w];for(let Y of $){if(!o$(Y)){J.push(Y);continue}let U=["id","name","key","path","type"],Z=!1;for(let B of U)if(B in Y){if(J.find((E)=>o$(E)&&(B in E)&&E[B]===Y[B])){Z=!0;break}}if(!Z)J.push(Y)}return J}function GG($,w,A,J){let Y=w;if(o$(Y)&&J.has(Y))return J.get(Y);let U={...$};if(o$(Y))J.set(Y,U);for(let Z in Y){if(!Object.prototype.hasOwnProperty.call(Y,Z))continue;let B=Y[Z],W=U[Z];if(A.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){U[Z]=B;continue}if(o$(B)&&o$(W))U[Z]=VB(W,B,A,J);else if(Array.isArray(B)||Array.isArray(W))U[Z]=SB(W,B,A.arrayMergeMode||"smart",J);else U[Z]=B}return U}function xU($,w,A="replace"){return yB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function RU($,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(!RU($[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 Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!RU($[Y],w[Y]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class aA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:Y=!0,cacheTtl:U,trackPerformance:Z=!0,verbose:B=!1}=A;if(Y){let E=uw.getWithFileCheck("file",$);if(E){if(B)console.log(`Configuration loaded from cache: ${$}`);return E}}let W=async()=>{if(!NA($))return null;try{let E=`?t=${Date.now()}`,j=await import($+E),F=j.default||j,f="default"in j,z=Object.keys(j).length>0;if(!f&&!z)throw new S1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new S1($,Error("Configuration must export a valid object"),"unknown");let q={config:xU(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)uw.setWithFileCheck("file",q,$,U);return q}catch(E){throw E instanceof Error?s0.configLoad($,E):s0.configLoad($,Error(String(E)))}};if(Z)return X1.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let Y=await this.loadFromPath(J,w,A);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(A.verbose)console.warn(`Failed to load config from ${J}:`,Y)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),Y=[];for(let U of J)for(let Z of this.extensions)Y.push(WU(w,`${U}${Z}`));return Y}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 CB(async()=>{return NA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!NA($))return J;if(w||A){let Y=this.generateNamePatterns(w||"",A);for(let U of Y)for(let Z of this.extensions){let B=WU($,`${U}${Z}`);if(await this.checkFileAccess(B))J.push(B)}}else try{let{readdirSync:Y}=await import("fs"),U=Y($);for(let Z of U)if(this.looksLikeConfigFile(Z)){let B=WU($,Z);if(await this.checkFileAccess(B))J.push(B)}}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:Y}=await import("fs"),U=Y($,"utf8");JSON.parse(U)}catch(Y){w.push(`Invalid JSON syntax: ${Y}`)}}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 Y=await this.loadFromPath(J,{},w);if(Y)A.set(J,Y.config)}catch(Y){if(w.verbose)console.warn(`Failed to preload ${J}:`,Y)}})),A}}class PU{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:Y=!0,validateTypes:U=!0,customRules:Z=[],trackPerformance:B=!0,verbose:W=!1}=A,E=async()=>{let j=[],F=[],f={stopOnFirstError:J,validateRequired:Y,validateTypes:U,customRules:Z,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,f);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Z],f);else return this.validateWithJSONSchema($,w,f)}catch(z){return j.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:j,warnings:F}}};if(B)return await X1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!Sf(w))throw new O1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),Y=J.default||J;if(Array.isArray(Y))return this.validateWithRules($,Y,A);else return this.validateWithJSONSchema($,Y,A)}catch(J){throw new O1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],Y=[];return this.validateObjectAgainstSchema($,w,"",J,Y,A),{isValid:J.length===0,errors:J,warnings:Y}}validateObjectAgainstSchema($,w,A,J,Y,U){if(U.validateTypes&&w.type){let Z=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(Z)){if(J.push({path:A,message:`Expected type ${B.join(" or ")}, got ${Z}`,expected:B.join(" or "),actual:Z,rule:"type"}),U.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"}),U.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 Z=0;Z<$.length;Z++){let B=A?`${A}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema($[Z],w.items,B,J,Y,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Z=$;if(U.validateRequired&&w.required){for(let B of w.required)if(!(B in Z)){if(J.push({path:A?`${A}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in Z){let E=A?`${A}.${B}`:B;if(this.validateObjectAgainstSchema(Z[B],W,E,J,Y,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(Z))if(!B.has(W))Y.push({path:A?`${A}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],Y=[];for(let U of w)try{let Z=this.getValueByPath($,U.path),B=this.validateWithRule(Z,U,U.path);if(J.push(...B),A.stopOnFirstError&&J.length>0)break}catch(Z){J.push({path:U.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:Y}}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 Y=Array.isArray($)?"array":typeof $;if(Y!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${Y}`,expected:w.type,actual:Y,rule:"type"})}if(w.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:Y,rule:"min"})}if(w.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:Y,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 Y=w.validator($);if(Y)J.push({path:A,message:w.message||Y,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let Y of A)if(J&&typeof J==="object"&&Y in J)J=J[Y];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,Y,U,Z]=J;w.push({path:Y,required:!U,type:this.mapTypeScriptType(Z)})}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:xB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class bU{fileLoader=new aA;envProcessor=new rA;validator=new PU;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:Y,validate:U,...Z}=$;try{if(A?.enabled){let W=this.checkCache(Z.name||"",Z);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(Z,!0,A)}catch(W){let E=Z.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(E)throw W;B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let j=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),F=!j&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),f=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(E&&(f||j))throw W;if(F&&(!E||!f))B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(Y||U)await this.validateConfiguration(B.config,Y,U,Z.name);if(A?.enabled&&B)this.cacheResult(Z.name||"",B,A,Z);if(J?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:Z.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(W);if(J.slowThreshold&&W.duration>J.slowThreshold)E0.warn(`Slow configuration loading detected: ${W.duration}ms for ${Z.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw E0.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:Y,cwd:U,configDir:Z,defaultConfig:B,checkEnv:W=!0,arrayStrategy:E="replace",verbose:j=!1}=$,F=U||fw.cwd(),f=[],z=await this.loadLocalConfiguration(J,Y,F,Z,B,E,j,W,A);if(z)return f.push(...this.getLocalSearchPaths(J,Y,F,Z)),this.finalizeResult(z,f,W,J,j);let H=await this.loadHomeConfiguration(J,Y,B,E,j,W);if(H)return f.push(...this.getHomeSearchPaths(J,Y)),this.finalizeResult(H,f,W,J,j);let T=await this.loadPackageJsonConfiguration(J,Y,F,B,E,j,W);if(T)return f.push(D$(F,"package.json")),this.finalizeResult(T,f,W,J,j);if(f.push(...this.getAllSearchPaths(J,Y,F,Z)),w)throw s0.configNotFound(J,f,Y);return{...await this.applyEnvironmentVariables(J,B,W,j),warnings:[`No configuration file found for "${J}"${Y?` or alias "${Y}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,Y,U,Z,B,W){let E=B?y1($,Y,Z):Y,j=this.getLocalDirectories(A,J);for(let F of j){if(Z)E0.info(`Searching for configuration in: ${F}`);let f=this.fileLoader.generateConfigPaths($,F,w),z=await this.fileLoader.tryLoadFromPaths(f,E,{arrayStrategy:U,verbose:Z,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(z){if(Z)E0.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration($,w,A,J,Y,U){if(!$)return null;let Z=U?y1($,A,Y):A,B=[D$(Ow(),".config",$),D$(Ow(),".config"),Ow()];for(let W of B){if(Y)E0.info(`Checking home directory: ${W}`);let E=this.fileLoader.generateConfigPaths($,W,w),j=await this.fileLoader.tryLoadFromPaths(E,Z,{arrayStrategy:J,verbose:Y});if(j){if(Y)E0.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,J,Y,U,Z){let B=Z?y1($,J,U):J;try{let W=D$(A,"package.json");if(!KU(W))return null;let E=await import(W),j=E[$],F=$;if(!j&&w)j=E[w],F=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(U)E0.success(`Configuration loaded from package.json: ${F}`);return{config:xU(B,j,Y),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(U)E0.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}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:y1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let Y=[];if(A){let U=A($);if(U)Y.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)Y.push(...U.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(Y.length>0)throw s0.configValidation(J||"unknown",Y,J)}checkCache($,w){let A=this.generateCacheKey($,w);return uw.get(A)||null}cacheResult($,w,A,J){let Y=this.generateCacheKey($,J);uw.set(Y,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 Y=[];return Y.push(...this.getLocalSearchPaths($,w,A,J)),Y.push(...this.getHomeSearchPaths($,w)),Y.push(D$(A,"package.json")),Y}getLocalSearchPaths($,w,A,J){let Y=this.getLocalDirectories(A,J),U=[];for(let Z of Y)U.push(...this.fileLoader.generateConfigPaths($,Z,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[D$(Ow(),".config",$),D$(Ow(),".config"),Ow()],J=[];for(let Y of A)J.push(...this.fileLoader.generateConfigPaths($,Y,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function YB($){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 TG($){return X0.loadConfig({...$,__strictErrorHandling:!0})}async function OB($){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 Y=J instanceof Error?J.name:"UnknownError",U=J instanceof Error?J.message:String(J);if(!(Y==="ConfigNotFoundError"||Y==="ConfigLoadError"||Y==="ConfigValidationError"||U.includes("config"))&&$.verbose)E0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let B=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await X0.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function HG($={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"&&YB(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"&&YB(w)))return(await X0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function qG($,w,A="replace"){let J=new aA;try{let Y=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return Y?Y.config:null}catch{return null}}function y1($,w,A=!1){let J=new rA,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=[`${Y}_${F.join("_").toUpperCase()}`,`${Y}_${F.map((T)=>T.toUpperCase()).join("")}`,`${Y}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,H;for(let T of f)if(z=fw.env[T],z!==void 0){H=T;break}if(z!==void 0&&H)if(typeof j==="boolean")W[E]=["true","1","yes"].includes(z.toLowerCase());else if(typeof j==="number"){let T=Number(z);if(!Number.isNaN(T))W[E]=T}else if(Array.isArray(j))try{W[E]=JSON.parse(z)}catch{W[E]=z.split(",").map((T)=>T.trim())}else W[E]=z;else if(j&&typeof j==="object"&&!Array.isArray(j))W[E]=U(j,F)}return W}return U(w)}function KG($){let w=D$(fw.cwd(),$.configDir),A=D$(fw.cwd(),$.generatedDir),J=D$(A,"config-types.ts");if(!KU(xW(J)))Uf(xW(J),{recursive:!0,mode:511});let Y=KU(w)?Zf(w).map((Z)=>Z.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],U=`// Generated by bunfig v${pG}
|
|
34
|
+
export type ConfigNames = ${Y.length?`'${Y.join("' | '")}'`:"string"}
|
|
35
|
+
`;Wf(J,U,{mode:438})}function hG($){let w=null,A=null,J=()=>{if(!A)A=OB($).then((U)=>{return w=U,U},(U)=>{let Z="defaultConfig"in $?$.defaultConfig:{};if(w=Z,"verbose"in $&&$.verbose)E0.warn("Config loading failed, using defaults:",[U instanceof Error?U:Error(String(U))]);return Z});return A},Y="defaultConfig"in $?$.defaultConfig:{};return w=Y,J(),new Proxy({},{get(U,Z){if(w)return w[Z];let B=Y[Z];return J(),B},has(U,Z){return Z in(w||Y)},ownKeys(){return Object.keys(w||Y)},getOwnPropertyDescriptor(U,Z){return Object.getOwnPropertyDescriptor(w||Y,Z)},set(U,Z,B){if(!w)w={...Y};return w[Z]=B,!0}})}function RG($){let w=aW(_f.cwd(),$?.configDir||"./config");function A(){if(!Of(w))return[];let Y=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),U=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Z=Xf(w).filter((W)=>Y.has(BU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:E}of Z){let j=BU(E).toLowerCase(),F=B.get(W);if(!F){B.set(W,E);continue}let f=BU(F).toLowerCase();if(U.indexOf(j)<U.indexOf(f))B.set(W,E)}return Array.from(B.entries()).map(([W,E])=>({base:W,file:E})).sort((W,E)=>W.base.localeCompare(E.base))}function J(){let Y=A(),U=Y.map((E)=>E.base),Z=U.length?U.map((E)=>`'${E}'`).join(" | "):"string",B=Y.length?`{
|
|
36
|
+
${Y.map((E)=>{let j=aW(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${j}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
39
|
-
export type ConfigByName = ${
|
|
38
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${Z}
|
|
39
|
+
export type ConfigByName = ${B}
|
|
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 T of
|
|
44
|
-
`;if(
|
|
45
|
-
`;if(
|
|
46
|
-
`);if(this[
|
|
47
|
-
`,
|
|
48
|
-
`),
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
42
|
+
`}return{name:"bunfig-plugin",setup(Y){Y.onResolve({filter:/^virtual:bunfig-types$/},(U)=>{return{path:U.path,namespace:"bunfig-virtual"}}),Y.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function rG($,w={}){let A=iA.cwd();while(A.includes("storage"))A=sW(A,"..");let J=sW(A,$||"");if(w?.relative)return Qf(iA.cwd(),J);return J}function B$(){if(O0.env.NODE_ENV==="test"||O0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sG(){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 uB{async format($){let w=await sG(),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:iw.pid,hostname:w(),environment:iw.env.NODE_ENV||"development",platform:iw.platform,version:iw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:iw.env.NODE_ENV||iw.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={...gA},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??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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,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{...HU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...HU};return{...HU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:gA.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 A=(async()=>{let Y,U=0,Z=3,B=1000;while(U<Z)try{try{try{await uf(this.config.logDirectory,wB.F_OK|wB.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await cf(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:L0.from($);try{if(!MA(this.currentLogFile))await FU(this.currentLogFile,"",{mode:420});if(Y=$B(this.currentLogFile,"a",420),bf(Y,W,{flag:"a"}),eW(Y),Y!==void 0)jU(Y),Y=void 0;if((await Pw(this.currentLogFile)).size===0){if(await FU(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(E){let j=E;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<Z-1){let F=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,F);let f=B*2**U;await new Promise((z)=>setTimeout(z,f)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{jU(Y)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(W){if(U===Z-1){let j=W,F=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),W}U++;let E=B*2**(U-1);await new Promise((j)=>setTimeout(j,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 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(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 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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Z=Math.max(1,U);if(Y.length>Z)for(let[B]of Y.slice(Z))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return EU(16).toString("hex")}generateKey(){return EU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=EU(16),J=kf("aes-256-gcm",w,A),Y=L0.isBuffer($)?$:L0.from($,"utf8"),U=J.update(Y),Z=J.final(),B=U.length+Z.length,W=J.getAuthTag(),E=L0.allocUnsafe(16+B+16);return A.copy(E,0),U.copy(E,16),Z.copy(E,16+U.length),W.copy(E,16+B),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=JB(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(L0.from(L0.concat(Y)))),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 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 Y=await IA(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await Pw(A).catch(()=>null))try{if(await AB(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await CA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await FU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await Pw(A).catch(()=>null))await AB(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await IA(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,B)=>B.localeCompare(Z));for(let Z of U.slice(w.maxFiles))await CA(bw(this.config.logDirectory,Z))}}}async compressLogFile($,w){let A=oW($),J=Pf(w),Y=JB();await nf(A,Y,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()})),MA(this.currentLogFile))try{let $=$B(this.currentLogFile,"r+");eW($),jU($)}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 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(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||B$())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:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=O.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${P.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,Y)=>{let U=P.underline(P.blue(J)),Z=this.toAbsoluteFilePath(Y);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(Z)}`,W="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${B}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),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(B$())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(vf(w)||w.startsWith("./")||w.startsWith("../"))w=mf(w);else return null;return MA(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,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);let{consoleText:W,fileText:E}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":A2[$],f=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:P.gray(W),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:P.green(W),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.error(z),B){let H=B.split(`
|
|
43
|
+
`);for(let T of H)if(T.trim()&&!T.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:P.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!B$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}let j=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
44
|
+
`;if(B)j+=`${B}
|
|
45
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!B$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!B$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!B$()&&O.stdout.isTTY)O.stdout.write(`
|
|
46
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!B$()&&O.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)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:A,message:`${P.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
47
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":P.green("✓"),tag:j,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!B$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}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(B$())throw Error("createReadStream is not supported in browser environments");if(!MA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return oW(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=L0.isBuffer($)?$:L0.from($,"base64"),Y=J.subarray(0,16),U=J.subarray(J.length-16),Z=J.subarray(16,J.length-16),B=xf("aes-256-gcm",A,Y);B.setAuthTag(U);let W=B.update(Z),E=B.final(),j=W.length+E.length,F=L0.allocUnsafe(j);return W.copy(F,0),E.copy(F,W.length),F.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 B$()}isServerMode(){return!B$()}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),{consoleText:Y,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=Y.split(`
|
|
48
|
+
`),W=Math.max(...B.map((f)=>f.length))+2,E=`┌${"─".repeat(W)}┐`,j=`└${"─".repeat(W)}┘`,F=B.map((f)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(f),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(E),showTimestamp:!1})),F.forEach((f)=>console.error(f)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(j),showTimestamp:!1}))}else if(!B$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${J} ${this.environment}.INFO: [BOX] ${U}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(B$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.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(Y==="y"||Y==="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 W=/%([sdijfo%])/g,E=0;if(A=$.replace(W,(j,F)=>{if(F==="%")return"%";if(E>=w.length)return j;let f=w[E++];switch(F){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return j}}),E<w.length)A+=` ${w.slice(E).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:J,fileText:Y}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${E}${W} ${P.cyan(J)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}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))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=P.green("━".repeat(J)),Z=P.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=O.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,O.stdout.write($.lastRenderedLine),w)O.stdout.write(`
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B$()||!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(B$()){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 J of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(J):J.startsWith(this.name))||!J.endsWith(".log"))continue;let U=bw(this.config.logDirectory,J);if($.before)try{if((await Pw(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);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 CA(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function J2($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:Y=()=>!0,fallback:U}=w,Z=Error("Unknown error occurred");for(let B=0;B<=A;B++)try{return await $()}catch(W){if(Z=W instanceof Error?W:Error(String(W)),B===A||!Y(Z))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}class uU{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:J,useCamelCase:Y=!0,useBackwardCompatibility:U=!0,customParsers:Z={},verbose:B=!1,trackPerformance:W=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],j,{useCamelCase:Y,useBackwardCompatibility:U,customParsers:Z,verbose:B,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return XU.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=Z.map((j)=>this.formatEnvKey(j,J.useCamelCase)),W=`${A}_${B.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Z.map((j)=>j.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Z,A,J);else{let j=yA.env[W]||(E?yA.env[E]:void 0);if(j!==void 0){if(J.verbose){let F=yA.env[W]?W:E}try{$[Y]=this.parseEnvironmentValue(j,typeof U,W,J.customParsers,J.configName)}catch(F){if(F instanceof iU)throw F;throw cw.envVar(W,j,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,Y){for(let[U,Z]of Object.entries(J))try{return Z($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw cw.envVar(A,$,`${w} (via ${U.name} parser)`,Y)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,Y]of Object.entries(yA.env))if(J.startsWith(A)&&Y!==void 0)w[J]=Y;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(Y){J.push(`Cannot parse value "${w}" as ${A}: ${Y}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:Y="text"}=A,U=J||this.generateEnvPrefix($),Z=[];switch(this.extractEnvVarInfo(w,[],U,Z),Y){case"markdown":return this.formatAsMarkdown(Z,$);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,$)}}extractEnvVarInfo($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=`${A}_${Z.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Z,A,J);else J.push({key:B,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Z.join(".")}`,example:this.generateExample(U)})}}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
52
|
|
|
53
53
|
`;for(let J of $)A+=`${J.key}
|
|
54
54
|
`,A+=` Type: ${J.type}
|
|
@@ -60,24 +60,24 @@ export type ConfigOf = Config
|
|
|
60
60
|
`;A+=`| Variable | Type | Description | Example |
|
|
61
61
|
`,A+=`|----------|------|-------------|----------|
|
|
62
62
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
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
|
-
`);for(let
|
|
65
|
-
`;if(W
|
|
66
|
-
`;
|
|
67
|
-
`,
|
|
68
|
-
`),
|
|
69
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
70
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||w$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,
|
|
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
|
-
`);for(let T of
|
|
73
|
-
`;if(
|
|
74
|
-
`;if(
|
|
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||
|
|
63
|
+
`;return A}}function Y2($,w,A={}){return pB($,w,A,new WeakMap)}function pB($,w,A,J){let{arrayMergeMode:Y="replace",skipNullish:U=!1,customMerger:Z}=A;if(w===null||w===void 0)return U?$:w;if(Z){let B=Z($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return tB($,w,Y,J);if(!e$(w)||!e$($))return w;return B2($,w,A,J)}function tB($,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 Z2($,w,J);default:return w}return w}function U2($,w){let A=[...w];for(let J of $)if(!A.some((Y)=>OU(Y,J)))A.push(J);return A}function Z2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(e$(w[0])&&e$($[0]))return W2($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}function W2($,w,A){let J=[...w];for(let Y of $){if(!e$(Y)){J.push(Y);continue}let U=["id","name","key","path","type"],Z=!1;for(let B of U)if(B in Y){if(J.find((E)=>e$(E)&&(B in E)&&E[B]===Y[B])){Z=!0;break}}if(!Z)J.push(Y)}return J}function B2($,w,A,J){let Y=w;if(e$(Y)&&J.has(Y))return J.get(Y);let U={...$};if(e$(Y))J.set(Y,U);for(let Z in Y){if(!Object.prototype.hasOwnProperty.call(Y,Z))continue;let B=Y[Z],W=U[Z];if(A.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){U[Z]=B;continue}if(e$(B)&&e$(W))U[Z]=pB(W,B,A,J);else if(Array.isArray(B)||Array.isArray(W))U[Z]=tB(W,B,A.arrayMergeMode||"smart",J);else U[Z]=B}return U}function rB($,w,A="replace"){return Y2($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function OU($,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(!OU($[A],w[A]))return!1;return!0}if(e$($)&&e$(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!OU($[Y],w[Y]))return!1}return!0}return!1}function e$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class aB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:Y=!0,cacheTtl:U,trackPerformance:Z=!0,verbose:B=!1}=A;if(Y){let E=kA.getWithFileCheck("file",$);if(E){if(B)console.log(`Configuration loaded from cache: ${$}`);return E}}let W=async()=>{if(!VA($))return null;try{let E=`?t=${Date.now()}`,j=await import($+E),F=j.default||j,f="default"in j,z=Object.keys(j).length>0;if(!f&&!z)throw new lA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new lA($,Error("Configuration must export a valid object"),"unknown");let q={config:rB(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)kA.setWithFileCheck("file",q,$,U);return q}catch(E){throw E instanceof Error?cw.configLoad($,E):cw.configLoad($,Error(String(E)))}};if(Z)return XU.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let Y=await this.loadFromPath(J,w,A);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(A.verbose)console.warn(`Failed to load config from ${J}:`,Y)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),Y=[];for(let U of J)for(let Z of this.extensions)Y.push(qU(w,`${U}${Z}`));return Y}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 U of J){if(!U)continue;if(A.push(U,`.${U}.config`,`${U}.config`,`.${U}`),$)A.push(`${$}.${U}.config`,`.${$}.${U}.config`)}let Y=new Set;return A.filter((U)=>{if(!U||Y.has(U))return!1;return Y.add(U),!0})}checkFileAccess($){return J2(async()=>{return VA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!VA($))return J;if(w||A){let Y=this.generateNamePatterns(w||"",A);for(let U of Y)for(let Z of this.extensions){let B=qU($,`${U}${Z}`);if(await this.checkFileAccess(B))J.push(B)}}else try{let{readdirSync:Y}=await import("fs"),U=Y($);for(let Z of U)if(this.looksLikeConfigFile(Z)){let B=qU($,Z);if(await this.checkFileAccess(B))J.push(B)}}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(!VA($))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:Y}=await import("fs"),U=Y($,"utf8");JSON.parse(U)}catch(Y){w.push(`Invalid JSON syntax: ${Y}`)}}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 Y=await this.loadFromPath(J,{},w);if(Y)A.set(J,Y.config)}catch(Y){if(w.verbose)console.warn(`Failed to preload ${J}:`,Y)}})),A}}class sB{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:Y=!0,validateTypes:U=!0,customRules:Z=[],trackPerformance:B=!0,verbose:W=!1}=A,E=async()=>{let j=[],F=[],f={stopOnFirstError:J,validateRequired:Y,validateTypes:U,customRules:Z,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,f);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Z],f);else return this.validateWithJSONSchema($,w,f)}catch(z){return j.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:j,warnings:F}}};if(B)return await XU.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!E2(w))throw new pA(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),Y=J.default||J;if(Array.isArray(Y))return this.validateWithRules($,Y,A);else return this.validateWithJSONSchema($,Y,A)}catch(J){throw new pA(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],Y=[];return this.validateObjectAgainstSchema($,w,"",J,Y,A),{isValid:J.length===0,errors:J,warnings:Y}}validateObjectAgainstSchema($,w,A,J,Y,U){if(U.validateTypes&&w.type){let Z=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(Z)){if(J.push({path:A,message:`Expected type ${B.join(" or ")}, got ${Z}`,expected:B.join(" or "),actual:Z,rule:"type"}),U.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"}),U.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 Z=0;Z<$.length;Z++){let B=A?`${A}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema($[Z],w.items,B,J,Y,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Z=$;if(U.validateRequired&&w.required){for(let B of w.required)if(!(B in Z)){if(J.push({path:A?`${A}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in Z){let E=A?`${A}.${B}`:B;if(this.validateObjectAgainstSchema(Z[B],W,E,J,Y,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(Z))if(!B.has(W))Y.push({path:A?`${A}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],Y=[];for(let U of w)try{let Z=this.getValueByPath($,U.path),B=this.validateWithRule(Z,U,U.path);if(J.push(...B),A.stopOnFirstError&&J.length>0)break}catch(Z){J.push({path:U.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:Y}}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 Y=Array.isArray($)?"array":typeof $;if(Y!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${Y}`,expected:w.type,actual:Y,rule:"type"})}if(w.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:Y,rule:"min"})}if(w.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:Y,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 Y=w.validator($);if(Y)J.push({path:A,message:w.message||Y,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let Y of A)if(J&&typeof J==="object"&&Y in J)J=J[Y];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,Y,U,Z]=J;w.push({path:Y,required:!U,type:this.mapTypeScriptType(Z)})}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:j2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function F2($){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 oB{fileLoader=new aB;envProcessor=new uU;validator=new sB;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:Y,validate:U,...Z}=$;try{if(A?.enabled){let W=this.checkCache(Z.name||"",Z);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(Z,!0,A)}catch(W){let E=Z.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(E)throw W;B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let j=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),F=!j&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),f=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(E&&(f||j))throw W;if(F&&(!E||!f))B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(Y||U)await this.validateConfiguration(B.config,Y,U,Z.name);if(A?.enabled&&B)this.cacheResult(Z.name||"",B,A,Z);if(J?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:Z.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(W);if(J.slowThreshold&&W.duration>J.slowThreshold)y0.warn(`Slow configuration loading detected: ${W.duration}ms for ${Z.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw y0.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:Y,cwd:U,configDir:Z,defaultConfig:B,checkEnv:W=!0,arrayStrategy:E="replace",verbose:j=!1}=$,F=U||tA.cwd(),f=[],z=await this.loadLocalConfiguration(J,Y,F,Z,B,E,j,W,A);if(z)return f.push(...this.getLocalSearchPaths(J,Y,F,Z)),this.finalizeResult(z,f,W,J,j);let H=await this.loadHomeConfiguration(J,Y,B,E,j,W);if(H)return f.push(...this.getHomeSearchPaths(J,Y)),this.finalizeResult(H,f,W,J,j);let T=await this.loadPackageJsonConfiguration(J,Y,F,B,E,j,W);if(T)return f.push(s$(F,"package.json")),this.finalizeResult(T,f,W,J,j);if(f.push(...this.getAllSearchPaths(J,Y,F,Z)),w)throw cw.configNotFound(J,f,Y);return{...await this.applyEnvironmentVariables(J,B,W,j),warnings:[`No configuration file found for "${J}"${F2(Y)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,Y,U,Z,B,W){let E=B?SA($,Y,Z):Y,j=this.getLocalDirectories(A,J);for(let F of j){if(Z)y0.info(`Searching for configuration in: ${F}`);let f=this.fileLoader.generateConfigPaths($,F,w),z=await this.fileLoader.tryLoadFromPaths(f,E,{arrayStrategy:U,verbose:Z,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(z){if(Z)y0.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration($,w,A,J,Y,U){if(!$)return null;let Z=U?SA($,A,Y):A,B=[s$(Sw(),".config",$),s$(Sw(),".config"),Sw()];for(let W of B){if(Y)y0.info(`Checking home directory: ${W}`);let E=this.fileLoader.generateConfigPaths($,W,w),j=await this.fileLoader.tryLoadFromPaths(E,Z,{arrayStrategy:J,verbose:Y});if(j){if(Y)y0.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,J,Y,U,Z){let B=Z?SA($,J,U):J;try{let W=s$(A,"package.json");if(!Jf(W))return null;let E={};try{E=JSON.parse(Yf(W,"utf8"))}catch(f){if(U)y0.warn("Failed to parse package.json:",[f instanceof Error?f:Error(String(f))]);return null}let j=E[$],F=$;if(!j&&w){let f=Array.isArray(w)?w:[w];for(let z of f){if(!z)continue;if(E[z]){j=E[z],F=z;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(U)y0.success(`Configuration loaded from package.json: ${F}`);return{config:rB(B,j,Y),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(U)y0.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}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:SA($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let Y=[];if(A){let U=A($);if(U)Y.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)Y.push(...U.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(Y.length>0)throw cw.configValidation(J||"unknown",Y,J)}checkCache($,w){let A=this.generateCacheKey($,w);return kA.get(A)||null}cacheResult($,w,A,J){let Y=this.generateCacheKey($,J);kA.set(Y,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([$,s$($,"config"),s$($,".config"),w?s$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let Y=[];return Y.push(...this.getLocalSearchPaths($,w,A,J)),Y.push(...this.getHomeSearchPaths($,w)),Y.push(s$(A,"package.json")),Y}getLocalSearchPaths($,w,A,J){let Y=this.getLocalDirectories(A,J),U=[];for(let Z of Y)U.push(...this.fileLoader.generateConfigPaths($,Z,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[s$(Sw(),".config",$),s$(Sw(),".config"),Sw()],J=[];for(let Y of A)J.push(...this.fileLoader.generateConfigPaths($,Y,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function SA($,w,A=!1){let J=new uU,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=[`${Y}_${F.join("_").toUpperCase()}`,`${Y}_${F.map((T)=>T.toUpperCase()).join("")}`,`${Y}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,H;for(let T of f)if(z=tA.env[T],z!==void 0){H=T;break}if(z!==void 0&&H)if(typeof j==="boolean")W[E]=["true","1","yes"].includes(z.toLowerCase());else if(typeof j==="number"){let T=Number(z);if(!Number.isNaN(T))W[E]=T}else if(Array.isArray(j))try{W[E]=JSON.parse(z)}catch{W[E]=z.split(",").map((T)=>T.trim())}else W[E]=z;else if(j&&typeof j==="object"&&!Array.isArray(j))W[E]=U(j,F)}return W}return U(w)}var kA,XU,df,gf=($)=>$,pf=($,w)=>{for(var A in w)df($,A,{get:w[A],enumerable:!0,configurable:!0,set:lf.bind(w,A)})},tf=($,w)=>()=>($&&(w=$($=0)),w),NB,XB,uw,X1,_B,NG,MG,UB,XA,NU,N$,g,IG,ZB,CG,WB,LG,yG,zU,VG,BB,EB,fU,SG,OG,XG,_G,_A,DB,DG,M$,QG,kG,jB,DA,MU,W$,D,xG,FB,PG,zB,bG,iG,GU,uG,fB,GB,cG,TU,vG,mG,nG,dG,gG,QA,QB,lG,pG="0.15.6",l$,nA,S1,IU,CU,dA,LU,yU,O1,VU,SU,s0,kB,xB,E0,X0,PB,bB,tG,aG,iB,gA,Vh,H$,P,Sh,oG,Oh,eG,Xh,_h,TB,Dh,$2,w2,Qh,HB,kh,xh,Ph,bh,ih,HU,A2,uh,j0,cB,lA,vB,mB,iU,nB,dB,pA,gB,lB,cw,j2,y0,dh,gh,lh;var cU=h$(()=>{kA=new qB,XU=new KB,df=Object.defineProperty;NB={};pf(NB,{withErrorRecovery:()=>CB,tryLoadConfig:()=>qG,loadConfigWithResult:()=>TG,loadConfig:()=>OB,isRetryableError:()=>EG,isConfigNotFoundError:()=>BG,isBunfigError:()=>LB,globalPerformanceMonitor:()=>X1,globalCache:()=>uw,getEnvOrDefault:()=>jG,generateConfigTypes:()=>KG,defaultGeneratedDir:()=>bB,defaultConfigDir:()=>PB,deepMergeWithArrayStrategy:()=>xU,deepMerge:()=>yB,createLibraryConfig:()=>hG,config:()=>HG,bunfigPlugin:()=>RG,applyEnvVarsToConfig:()=>y1,TypeGenerationError:()=>yU,SchemaValidationError:()=>O1,PluginError:()=>SU,PerformanceMonitor:()=>DU,FileSystemError:()=>LU,ErrorFactory:()=>s0,EnvVarError:()=>dA,EnvProcessor:()=>rA,ConfigValidator:()=>PU,ConfigValidationError:()=>IU,ConfigNotFoundError:()=>nA,ConfigMergeError:()=>CU,ConfigLoader:()=>bU,ConfigLoadError:()=>S1,ConfigFileLoader:()=>aA,ConfigCache:()=>_U,CacheUtils:()=>_B,BunfigError:()=>l$,BrowserConfigError:()=>VU,ArrayMergeStrategies:()=>kB});tG=tf(async()=>{XB=import.meta.require,uw=new _U,X1=new DU,_B={createKey:rf,isEquivalent:af,estimateMemoryUsage:sf},NG=bA(hU.cwd(),"config"),MG=bA(hU.cwd(),"src/generated"),UB=PA.env.CLARITY_LOG_DIR||jf($G(),"logs"),XA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:UB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},NU=await wG(),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`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},g=N$,IG=N$.red,ZB=N$.green,CG=N$.yellow,WB=N$.blue,LG=N$.magenta,yG=N$.cyan,zU=N$.white,VG=N$.gray,BB=N$.bgRed,EB=N$.bgYellow,fU=N$.bold,SG=N$.dim,OG=N$.italic,XG=N$.underline,_G=N$.reset,_A={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},DB={debug:"\uD83D\uDD0D",info:WB("ℹ"),success:ZB("✓"),warning:EB(zU(fU(" WARN "))),error:BB(zU(fU(" ERROR ")))},DG=new cA("stacks"),M$=new cA("bunfig",{showTags:!0}),QG=_$(V1.cwd(),"config"),kG=_$(V1.cwd(),"src/generated"),jB=xA.env.CLARITY_LOG_DIR||Bf(UG(),"logs"),DA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},MU=await ZG(),W$={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=W$,xG=W$.red,FB=W$.green,PG=W$.yellow,zB=W$.blue,bG=W$.magenta,iG=W$.cyan,GU=W$.white,uG=W$.gray,fB=W$.bgRed,GB=W$.bgYellow,cG=W$.bgGray,TU=W$.bold,vG=W$.dim,mG=W$.italic,nG=W$.underline,dG=W$.strikethrough,gG=W$.reset,QA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QB={debug:"\uD83D\uDD0D",info:zB("ℹ"),success:FB("✓"),warning:GB(GU(TU(" WARN "))),error:fB(GU(TU(" ERROR ")))},lG=new mA("stacks"),l$=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}`}},nA=class extends l${code="CONFIG_NOT_FOUND";constructor(w,A,J){let Y=J?` or alias "${J}"`:"";super(`Configuration "${w}"${Y} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},S1=class extends l${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}},IU=class extends l${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},CU=class extends l${code="CONFIG_MERGE_ERROR";constructor(w,A,J,Y){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:Y,originalError:J.name,originalMessage:J.message});this.cause=J}},dA=class extends l${code="ENV_VAR_ERROR";constructor(w,A,J,Y){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:Y})}},LU=class extends l${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}},yU=class extends l${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}},O1=class extends l${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})}},VU=class extends l${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,Y){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:Y})}},SU=class extends l${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}},s0={configNotFound($,w,A){return new nA($,w,A)},configLoad($,w,A){return new S1($,w,A)},configValidation($,w,A){return new IU($,w,A)},configMerge($,w,A,J){return new CU($,w,A,J)},envVar($,w,A,J){return new dA($,w,A,J)},fileSystem($,w,A){return new LU($,w,A)},typeGeneration($,w,A){return new yU($,w,A)},schemaValidation($,w,A){return new O1($,w,A)},browserConfig($,w,A,J){return new VU($,w,A,J)},plugin($,w,A){return new SU($,w,A)}},kB={replace:"replace",concat:"concat",smart:"smart"},xB=/^https?:\/\//,E0=new mA("bunfig",{showTags:!0}),X0=new bU,PB=D$(fw.cwd(),"config"),bB=D$(fw.cwd(),"src/generated")});aG=iA.env.CLARITY_LOG_DIR||Df(rG(),"logs"),iB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},gA={...iB},Vh=(async()=>{try{let{loadConfig:$}=await tG().then(()=>NB),w=await $({name:"clarity",alias:"logging",defaultConfig:iB,cwd:iA.cwd()});if(w)Object.assign(gA,w)}catch{}return gA})();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"},P=H$,Sh=H$.red,oG=H$.green,Oh=H$.yellow,eG=H$.blue,Xh=H$.magenta,_h=H$.cyan,TB=H$.white,Dh=H$.gray,$2=H$.bgRed,w2=H$.bgYellow,Qh=H$.bgGray,HB=H$.bold,kh=H$.dim,xh=H$.italic,Ph=H$.underline,bh=H$.strikethrough,ih=H$.reset,HU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},A2={debug:"\uD83D\uDD0D",info:eG("ℹ"),success:oG("✓"),warning:w2(TB(HB(" WARN "))),error:$2(TB(HB(" ERROR ")))};uh=new sA("stacks");j0=class j0 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}${$}`}};cB=class cB extends j0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],Y="";if(J.length===1)Y=` or alias "${J[0]}"`;else if(J.length>1)Y=` or aliases ${J.map((U)=>`"${U}"`).join(", ")}`;super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};lA=class lA extends j0{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}};vB=class vB extends j0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};mB=class mB extends j0{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}};iU=class iU extends j0{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})}};nB=class nB extends j0{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}};dB=class dB extends j0{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}};pA=class pA extends j0{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 j0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}};lB=class lB extends j0{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}};cw={configNotFound($,w,A){return new cB($,w,A)},configLoad($,w,A){return new lA($,w,A)},configValidation($,w,A){return new vB($,w,A)},configMerge($,w,A,J){return new mB($,w,A,J)},envVar($,w,A,J){return new iU($,w,A,J)},fileSystem($,w,A){return new nB($,w,A)},typeGeneration($,w,A){return new dB($,w,A)},schemaValidation($,w,A){return new pA($,w,A)},browserConfig($,w,A,J){return new gB($,w,A,J)},plugin($,w,A){return new lB($,w,A)}};j2=/^https?:\/\//;y0=new sA("bunfig",{showTags:!0});dh=new oB;gh=s$(tA.cwd(),"config"),lh=s$(tA.cwd(),"src/generated")});var R;var o0=h$(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as G2}from"node:module";import nU from"node:os";import dU from"node:path";import{existsSync as eB,statSync as $E}from"fs";import{existsSync as T2,mkdirSync as ZR,readdirSync as WR,readFileSync as H2,writeFileSync as BR}from"fs";import{homedir as mw}from"os";import{dirname as FR,resolve as $0}from"path";import QJ from"process";import{existsSync as wE,statSync as AE}from"fs";import{existsSync as j8,mkdirSync as q2,readdirSync as K2,writeFileSync as h2}from"fs";import{homedir as nw}from"os";import{dirname as JE,resolve as k$}from"path";import Gw from"process";import{join as R2,relative as N2,resolve as YE}from"path";import qJ from"process";import{existsSync as gE,mkdirSync as NR,readdirSync as MR,writeFileSync as IR}from"fs";import{homedir as gU}from"os";import{dirname as yR,resolve as Q$}from"path";import k1 from"process";import{join as M2,relative as I2,resolve as UE}from"path";import KJ from"process";import{existsSync as lE,mkdirSync as _R,readdirSync as DR,writeFileSync as QR}from"fs";import{dirname as xR,resolve as hJ}from"path";import F8 from"process";import{Buffer as e0}from"buffer";import{createCipheriv as C2,createDecipheriv as L2,randomBytes as lU}from"crypto";import{closeSync as pU,createReadStream as ZE,createWriteStream as y2,existsSync as tU,fsyncSync as WE,openSync as BE,writeFileSync as V2}from"fs";import{access as S2,constants as EE,mkdir as O2,readdir as oA,rename as jE,stat as dw,unlink as eA,writeFile as rU}from"fs/promises";import{join as gw}from"path";import I$ from"process";import{pipeline as X2}from"stream/promises";import{createGzip as FE}from"zlib";import lw from"process";import k0 from"process";import{Buffer as _0}from"buffer";import{createCipheriv as _2,createDecipheriv as D2,randomBytes as aU}from"crypto";import{closeSync as sU,createReadStream as zE,createWriteStream as Q2,existsSync as $J,fsyncSync as fE,openSync as GE,writeFileSync as k2}from"fs";import{access as x2,constants as TE,mkdir as P2,readdir as wJ,rename as HE,stat as pw,unlink as AJ,writeFile as oU}from"fs/promises";import{isAbsolute as b2,join as tw,resolve as i2}from"path";import v from"process";import{pipeline as u2}from"stream/promises";import{createGzip as qE}from"zlib";import rw from"process";import x0 from"process";import JJ from"process";import{existsSync as YJ}from"fs";import{resolve as eU}from"path";import{existsSync as c2}from"fs";import{existsSync as v2,readdirSync as m2}from"fs";import{extname as $8,resolve as KE}from"path";import n2 from"process";import{join as d2,relative as g2,resolve as hE}from"path";import RJ from"process";import{Buffer as D0}from"buffer";import{createCipheriv as l2,createDecipheriv as p2,randomBytes as w8}from"crypto";import{closeSync as A8,createReadStream as RE,createWriteStream as t2,existsSync as UJ,fsyncSync as NE,openSync as ME,writeFileSync as r2}from"fs";import{access as a2,constants as IE,mkdir as s2,readdir as ZJ,rename as CE,stat as aw,unlink as WJ,writeFile as J8}from"fs/promises";import{isAbsolute as o2,join as sw,resolve as e2}from"path";import m from"process";import{pipeline as $T}from"stream/promises";import{createGzip as LE}from"zlib";import ow from"process";import P0 from"process";import BJ from"process";import{existsSync as EJ}from"fs";import{resolve as Y8}from"path";import{existsSync as wT}from"fs";import{exec as IH}from"node:child_process";import uE from"node:fs";import CH from"node:os";import F0 from"node:path";import Sj from"node:process";import{promisify as LH}from"node:util";import A1 from"node:crypto";import b0 from"node:fs";import C8 from"node:path";import{execSync as dE}from"node:child_process";import DJ from"node:os";class pE{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 Y=this.generateKey($,A),U=J??this.options.ttl,Z=this.estimateSize(w);this.cache.set(Y,{value:w,timestamp:new Date,ttl:U,hits:0,size:Z}),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(!eB($))return!0;return $E($).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 Y=eB(A)?$E(A):null,U=Y?Y.mtime:new Date;this.set($,{value:w,fileTimestamp:U},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,Y)=>J+Y.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 tE{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),Y=new Date;try{let U=await w(),Z=performance.now()-J;return this.recordMetric({operation:$,duration:Z,timestamp:Y,...A}),U}catch(U){let Z=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Z,timestamp:Y,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((Y)=>Y.duration),J=A.reduce((Y,U)=>Y+U,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 YT($,w){this[$]=JT.bind(null,w)}class y8{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 Y=this.generateKey($,A),U=J??this.options.ttl,Z=this.estimateSize(w);this.cache.set(Y,{value:w,timestamp:new Date,ttl:U,hits:0,size:Z}),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(!wE($))return!0;return AE($).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 Y=wE(A)?AE(A):null,U=Y?Y.mtime:new Date;this.set($,{value:w,fileTimestamp:U},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,Y)=>J+Y.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 V8{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),Y=new Date;try{let U=await w(),Z=performance.now()-J;return this.recordMetric({operation:$,duration:Z,timestamp:Y,...A}),U}catch(U){let Z=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Z,timestamp:Y,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((Y)=>Y.duration),J=A.reduce((Y,U)=>Y+U,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 WT($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function BT($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function ET($){return $.getStats().size*2}function S8($,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 Y of $)if(a(Y)&&"name"in Y){if(!J.find((U)=>a(U)&&("name"in U)&&U.name===Y.name))J.push(Y)}else if(a(Y)&&"path"in Y){if(!J.find((U)=>a(U)&&("path"in U)&&U.path===Y.path))J.push(Y)}else if(!J.some((U)=>MJ(U,Y)))J.push(Y);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);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 Y=w[J];if(Y===null||Y===void 0)continue;else if(a(Y)&&a(A[J]))A[J]=S8(A[J],Y);else if(Array.isArray(Y)&&Array.isArray(A[J]))if(Y.length>0&&A[J].length>0&&a(Y[0])&&a(A[J][0])){let U=[...Y];for(let Z of A[J])if(a(Z)&&"name"in Z){if(!U.find((B)=>a(B)&&("name"in B)&&B.name===Z.name))U.push(Z)}else if(a(Z)&&"path"in Z){if(!U.find((B)=>a(B)&&("path"in B)&&B.path===Z.path))U.push(Z)}else if(!U.some((B)=>MJ(B,Z)))U.push(Z);A[J]=U}else if(Y.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...Y];for(let Z of A[J])if(!U.includes(Z))U.push(Z);A[J]=U}else A[J]=Y;else A[J]=Y}return A}function MJ($,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(!MJ($[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 Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!MJ($[Y],w[Y]))return!1}return!0}return!1}function a($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function jT($,w){if(!lE($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return S8(w,J)}catch{return null}}catch{return null}}async function FT({name:$="",cwd:w,defaultConfig:A}){let J=w||F8.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Z of U)for(let B of Y){let W=hJ(J,`${Z}${B}`),E=await jT(W,A);if(E!==null)return E}try{let Z=hJ(J,"package.json");if(lE(Z)){let B=(await import(Z))[$];if(B&&typeof B==="object"&&!Array.isArray(B))try{return S8(A,B)}catch{}}}catch{}return A}function zT($,w={}){let A=KJ.cwd();while(A.includes("storage"))A=UE(A,"..");let J=UE(A,$||"");if(w?.relative)return I2(KJ.cwd(),J);return J}async function fT(){try{let $=await FT({name:"clarity",defaultConfig:fJ,cwd:KJ.cwd(),endpoint:"",headers:{}});return{...fJ,...$}}catch{return fJ}}function w$(){if(k0.env.NODE_ENV==="test"||k0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function GT(){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 GT(),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 IJ{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...f8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new 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??I$.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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...GJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...GJ};return{...GJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:f8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},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,Y=0,U=3,Z=1000;while(Y<U)try{try{try{await S2(this.config.logDirectory,EE.F_OK|EE.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await O2(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:e0.from($);try{if(!tU(this.currentLogFile))await rU(this.currentLogFile,"",{mode:420});if(J=BE(this.currentLogFile,"a",420),V2(J,B,{flag:"a"}),WE(J),J!==void 0)pU(J),J=void 0;if((await dw(this.currentLogFile)).size===0){if(await rU(this.currentLogFile,B,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let E=W;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${U}:`,j);let F=Z*2**Y;await new Promise((f)=>setTimeout(f,F)),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(J!==void 0)try{pU(J)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(Y===U-1){let E=B,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),B}Y++;let W=Z*2**(Y-1);await new Promise((E)=>setTimeout(E,W))}})();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(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(([,Z],[,B])=>B.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,Y);if(J.length>U)for(let[Z]of J.slice(U))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return lU(16).toString("hex")}generateKey(){return lU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=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=lU(16),J=C2("aes-256-gcm",w,A),Y=e0.concat([J.update($,"utf8"),J.final()]),U=J.getAuthTag();return{encrypted:e0.concat([A,Y,U]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=FE(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(e0.from(e0.concat(Y)))),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 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 Y=await oA(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await dw(A).catch(()=>null))try{if(await jE(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await eA(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await rU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await dw(A).catch(()=>null))await jE(A,U)}if(this.currentLogFile=J,w.maxFiles){let Y=(await oA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Z)=>Z.localeCompare(U));for(let U of Y.slice(w.maxFiles))await eA(gw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=ZE($),J=y2(w),Y=FE();await X2(A,Y,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()})),tU(this.currentLogFile))try{let $=BE(this.currentLogFile,"r+");WE($),pU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!w$()&&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(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.fancy?l.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=I$.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${l.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}async log($,w,...A){let J=new Date,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);if(this.fancy&&!w$()){let E=Zj[$],j=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:l.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:l.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.error(F),B){let f=B.split(`
|
|
64
|
+
`);for(let z of f)if(z.trim()&&!z.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:l.gray(` ${z}`),level:$,showTimestamp:!1}))}break}}else if(!w$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${U} ${this.environment}.${$.toUpperCase()}: ${Z}
|
|
65
|
+
`;if(B)W+=`${B}
|
|
66
|
+
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!w$()){let A=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:l.blue("◐"),tag:A,message:`${l.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),W=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
67
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!w$()){let E=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:l.green("✓"),tag:E,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!w$())console.error(W.trim());await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 IJ(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(!tU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ZE(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=e0.isBuffer($)?$:e0.from($,"base64"),Y=J.slice(0,16),U=J.slice(-16),Z=J.slice(16,-16),B=L2("aes-256-gcm",A,Y);return B.setAuthTag(U),e0.concat([B.update(Z),B.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 U=$.split(`
|
|
68
|
+
`),Z=Math.max(...U.map((j)=>j.length))+2,B=`┌${"─".repeat(Z)}┐`,W=`└${"─".repeat(Z)}┘`,E=U.map((j)=>{let F=" ".repeat(Z-j.length-2);return`│ ${j}${F} │`});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(B)})),E.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(W),showTimestamp:!1}))}else if(!w$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
69
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt($){if(w$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${l.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.toString().trim().toLowerCase();I$.stdin.removeListener("data",A);try{if(typeof I$.stdin.setRawMode==="function")I$.stdin.setRawMode(!1)}catch{}I$.stdin.pause(),console.error(""),w(Y==="y"||Y==="yes")};try{if(typeof I$.stdin.setRawMode==="function")I$.stdin.setRawMode(!0)}catch{}I$.stdin.resume(),I$.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 Y=/%([sdijfo%])/g,U=0;if(A=$.replace(Y,(Z,B)=>{if(B==="%")return"%";if(U>=w.length)return Z;let W=w[U++];switch(B){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 Z}}),U<w.length)A+=` ${w.slice(U).map((Z)=>typeof Z==="object"?JSON.stringify(Z,null,2):String(Z)).join(" ")}`}if(this.fancy&&!w$()){let Y=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",U=l.blue("◐");console.error(`${U} ${Y} ${l.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
70
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||w$()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),Y!==void 0)this.activeProgressBar.message=Y;let U=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,U)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,Y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w$())return;I$.stdout.write(`${"\r".padEnd(I$.stdout.columns||80)}\r`),this.log(Y,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||w$()||!I$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=l.green("━".repeat(J)),Z=l.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=w||A===100?l.green("✓"):l.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${l.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=I$.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,I$.stdout.write($.lastRenderedLine),w)I$.stdout.write(`
|
|
71
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||w$()||!I$.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 oA(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=gw(this.config.logDirectory,J);if($.before)try{if((await dw(Y)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${Y}:`,U);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 eA(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function zJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&n(w[0])&&"id"in w[0]&&w[0].id===3&&n(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(n(w)&&n($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(n($)&&"arr"in $&&Array.isArray($.arr)&&n(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&n(w[0])&&n($[0])){let J=[...w];for(let Y of $)if(n(Y)&&"name"in Y){if(!J.find((U)=>n(U)&&("name"in U)&&U.name===Y.name))J.push(Y)}else if(n(Y)&&"path"in Y){if(!J.find((U)=>n(U)&&("path"in U)&&U.path===Y.path))J.push(Y)}else if(!J.some((U)=>CJ(U,Y)))J.push(Y);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}if(!n(w)||!n($))return w;let A={...$};for(let J in w)if(Object.prototype.hasOwnProperty.call(w,J)){let Y=w[J];if(Y===null||Y===void 0)continue;else if(n(Y)&&n(A[J]))A[J]=zJ(A[J],Y);else if(Array.isArray(Y)&&Array.isArray(A[J]))if(Y.length>0&&A[J].length>0&&n(Y[0])&&n(A[J][0])){let U=[...Y];for(let Z of A[J])if(n(Z)&&"name"in Z){if(!U.find((B)=>n(B)&&("name"in B)&&B.name===Z.name))U.push(Z)}else if(n(Z)&&"path"in Z){if(!U.find((B)=>n(B)&&("path"in B)&&B.path===Z.path))U.push(Z)}else if(!U.some((B)=>CJ(B,Z)))U.push(Z);A[J]=U}else if(Y.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...Y];for(let Z of A[J])if(!U.includes(Z))U.push(Z);A[J]=U}else A[J]=Y;else A[J]=Y}return A}function O8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:zJ($,w);if(Array.isArray($))return A==="replace"?w:zJ($,w);if(!n(w)||!n($))return w;let J={...$};for(let Y of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,Y))continue;let U=w[Y],Z=J[Y];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Z))if(A==="replace")J[Y]=U;else J[Y]=zJ(Z,U);else if(n(U)&&n(Z))J[Y]=O8(Z,U,A);else J[Y]=U}return J}function CJ($,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(!CJ($[A],w[A]))return!1;return!0}if(n($)&&n(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!CJ($[Y],w[Y]))return!1}return!0}return!1}function n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function jJ($,w,A="replace"){if(!gE($))return null;try{let J=await import($),Y=J.default||J;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return O8(w,Y,A)}catch{return null}}catch{return null}}function TT($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),Y={...w};function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${J}_${F.map(f).join("_")}`,H=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)L$.info(`Checking environment variable ${z} for config ${$}.${F.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))W[E]=U(j,F);else{let T=k1.env[z]||k1.env[H];if(T!==void 0){if(A)L$.info(`Using environment variable ${T?z:H} for config ${$}.${F.join(".")}`);if(typeof j==="number")W[E]=Number(T);else if(typeof j==="boolean")W[E]=T.toLowerCase()==="true";else if(Array.isArray(j))try{let q=JSON.parse(T);if(Array.isArray(q))W[E]=q;else W[E]=T.split(",").map((K)=>K.trim())}catch{W[E]=T.split(",").map((q)=>q.trim())}else W[E]=T}}}return W}return U(Y)}async function HT({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:Y,verbose:U=!1,checkEnv:Z=!0,arrayStrategy:B="replace"}){let W=Z&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?TT($,Y,U):Y,E=A||k1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(U)L$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),f=[`${$}.config`,`.${$}.config`].filter(Boolean),z=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([E,Q$(E,"config"),Q$(E,".config"),J?Q$(E,J):void 0].filter(Boolean)));for(let q of T){if(U)L$.info(`Searching for configuration in: ${q}`);let K=[Q$(E,"config"),Q$(E,".config")].concat(J?[Q$(E,J)]:[]).includes(q)?[...F,...f,...z,...H]:[...f,...F,...H,...z];for(let h of K)for(let I of j){let N=Q$(q,`${h}${I}`),M=await jJ(N,W,B);if(M!==null){if(U)L$.success(`Configuration loaded from: ${N}`);return M}}}if($){let q=Q$(gU(),".config",$),K=["config",`${$}.config`];if(w)K.push(`${w}.config`);if(U)L$.info(`Checking user config directory: ${q}`);for(let h of K)for(let I of j){let N=Q$(q,`${h}${I}`),M=await jJ(N,W,B);if(M!==null){if(U)L$.success(`Configuration loaded from user config directory: ${N}`);return M}}}if($){let q=Q$(gU(),".config"),K=[`.${$}.config`];if(w)K.push(`.${w}.config`);if(U)L$.info(`Checking user config directory for dotfile configs: ${q}`);for(let h of K)for(let I of j){let N=Q$(q,`${h}${I}`),M=await jJ(N,W,B);if(M!==null){if(U)L$.success(`Configuration loaded from user config directory dotfile: ${N}`);return M}}}if($){let q=gU(),K=[`.${$}.config`,`.${$}`];if(w)K.push(`.${w}.config`),K.push(`.${w}`);if(U)L$.info(`Checking user home directory for dotfile configs: ${q}`);for(let h of K)for(let I of j){let N=Q$(q,`${h}${I}`),M=await jJ(N,W,B);if(M!==null){if(U)L$.success(`Configuration loaded from user home directory: ${N}`);return M}}}try{let q=Q$(E,"package.json");if(gE(q)){let K=await import(q),h=K[$];if(!h&&w){if(h=K[w],h&&U)L$.success(`Using alias "${w}" configuration from package.json`)}if(h&&typeof h==="object"&&!Array.isArray(h))try{if(U)L$.success(`Configuration loaded from package.json: ${h===K[$]?$:w}`);return O8(W,h,B)}catch(I){if(U)L$.warn("Failed to merge package.json config:",I)}}}catch(q){if(U)L$.warn("Failed to load package.json:",q)}if(U)L$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function qT($,w={}){let A=qJ.cwd();while(A.includes("storage"))A=YE(A,"..");let J=YE(A,$||"");if(w?.relative)return N2(qJ.cwd(),J);return J}async function KT(){try{let $=await HT({name:"clarity",alias:"logging",defaultConfig:TJ,cwd:qJ.cwd()});return{...TJ,...$||{}}}catch{return TJ}}function E$(){if(x0.env.NODE_ENV==="test"||x0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hT(){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 sE{async format($){let w=await hT(),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 LJ{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={...G8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new sE,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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,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{...HJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...HJ};return{...HJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:G8.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!E$()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let J,Y=0,U=3,Z=1000;while(Y<U)try{try{try{await x2(this.config.logDirectory,TE.F_OK|TE.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await P2(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:_0.from($);try{if(!$J(this.currentLogFile))await oU(this.currentLogFile,"",{mode:420});if(J=GE(this.currentLogFile,"a",420),k2(J,B,{flag:"a"}),fE(J),J!==void 0)sU(J),J=void 0;if((await pw(this.currentLogFile)).size===0){if(await oU(this.currentLogFile,B,{flag:"w",mode:420}),(await pw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let E=W;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${U}:`,j);let F=Z*2**Y;await new Promise((f)=>setTimeout(f,F)),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(J!==void 0)try{sU(J)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(Y===U-1){let E=B,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),B}Y++;let W=Z*2**(Y-1);await new Promise((E)=>setTimeout(E,W))}})();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(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 $=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(([,Z],[,B])=>B.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,Y);if(J.length>U)for(let[Z]of J.slice(U))this.encryptionKeys.delete(Z),this.keys.delete(Z)}generateKeyId(){return aU(16).toString("hex")}generateKey(){return aU(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=aU(16),J=_2("aes-256-gcm",w,A),Y=_0.isBuffer($)?$:_0.from($,"utf8"),U=J.update(Y),Z=J.final(),B=U.length+Z.length,W=J.getAuthTag(),E=_0.allocUnsafe(16+B+16);return A.copy(E,0),U.copy(E,16),Z.copy(E,16+U.length),W.copy(E,16+B),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=qE(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(_0.from(_0.concat(Y)))),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(E$())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 Y=await wJ(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await pw(A).catch(()=>null))try{if(await HE(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await AJ(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await oU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await pw(A).catch(()=>null))await HE(A,U)}if(this.currentLogFile=J,w.maxFiles){let Y=(await wJ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Z)=>Z.localeCompare(U));for(let U of Y.slice(w.maxFiles))await AJ(tw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=zE($),J=Q2(w),Y=qE();await u2(A,Y,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()})),$J(this.currentLogFile))try{let $=GE(this.currentLogFile,"r+");fE($),sU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await wJ(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await AJ(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()?Q.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:J="",message:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=v.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${Q.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,Y)=>{let U=Q.underline(Q.blue(J)),Z=this.toAbsoluteFilePath(Y);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(Z)}`,W="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${B}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),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(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(b2(w)||w.startsWith("./")||w.startsWith("../"))w=i2(w);else return null;return $J(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,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);let{consoleText:W,fileText:E}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":Wj[$],f=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:Q.gray(W),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:Q.green(W),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.error(z),B){let H=B.split(`
|
|
72
|
+
`);for(let T of H)if(T.trim()&&!T.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:Q.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!E$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}if(!this.shouldLog($))return;let j=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
73
|
+
`;if(B)j+=`${B}
|
|
74
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(Y,U)=>{},finish:(Y)=>{},interrupt:(Y,U)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!E$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Y,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Y),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!E$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Y)},interrupt:(Y,U="info")=>{if(!E$()&&v.stdout.isTTY)v.stdout.write(`
|
|
75
|
+
`);if(this[U==="warning"?"warn":U](Y),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?Q.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":Q.blue("◐"),tag:A,message:`${Q.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),W=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
76
|
+
`,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:E,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!E$())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 LJ(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(!$J(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zE(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=_0.isBuffer($)?$:_0.from($,"base64"),Y=J.subarray(0,16),U=J.subarray(J.length-16),Z=J.subarray(16,J.length-16),B=D2("aes-256-gcm",A,Y);B.setAuthTag(U);let W=B.update(Z),E=B.final(),j=W.length+E.length,F=_0.allocUnsafe(j);return W.copy(F,0),E.copy(F,W.length),F.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 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),J=this.formatFileTimestamp(w),{consoleText:Y,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=Y.split(`
|
|
77
|
+
`),W=Math.max(...B.map((f)=>f.length))+2,E=`┌${"─".repeat(W)}┐`,j=`└${"─".repeat(W)}┘`,F=B.map((f)=>{return this.formatConsoleMessage({timestamp:A,message:Q.cyan(f),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(E),showTimestamp:!1})),F.forEach((f)=>console.error(f)),console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(j),showTimestamp:!1}))}else if(!E$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${J} ${this.environment}.INFO: [BOX] ${U}
|
|
78
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(E$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${Q.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.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(Y==="y"||Y==="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 Z=/%([sdijfo%])/g,B=0;if(A=$.replace(Z,(W,E)=>{if(E==="%")return"%";if(B>=w.length)return W;let j=w[B++];switch(E){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 W}}),B<w.length)A+=` ${w.slice(B).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:J,fileText:Y}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${B}${Z} ${Q.cyan(J)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
79
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}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))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=Q.green("━".repeat(J)),Z=Q.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?Q.green("✓"):Q.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=v.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,v.stdout.write($.lastRenderedLine),w)v.stdout.write(`
|
|
80
|
+
`)}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 wJ(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=tw(this.config.logDirectory,J);if($.before)try{if((await pw(Y)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${Y}:`,U);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 AJ(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function oE($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:Y=()=>!0,fallback:U}=w,Z=Error("Unknown error occurred");for(let B=0;B<=A;B++)try{return await $()}catch(W){if(Z=W instanceof Error?W:Error(String(W)),B===A||!Y(Z))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}function eE($){return $ instanceof p$}function RT($){return $ instanceof yJ}function NT($){if(eE($))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 kJ{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:J,useCamelCase:Y=!0,useBackwardCompatibility:U=!0,customParsers:Z={},verbose:B=!1,trackPerformance:W=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],j,{useCamelCase:Y,useBackwardCompatibility:U,customParsers:Z,verbose:B,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return i1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=Z.map((j)=>this.formatEnvKey(j,J.useCamelCase)),W=`${A}_${B.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Z.map((j)=>j.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Z,A,J);else{let j=JJ.env[W]||(E?JJ.env[E]:void 0);if(j!==void 0){if(J.verbose){let F=JJ.env[W]?W:E}try{$[Y]=this.parseEnvironmentValue(j,typeof U,W,J.customParsers,J.configName)}catch(F){if(F instanceof VJ)throw F;throw ww.envVar(W,j,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,Y){for(let[U,Z]of Object.entries(J))try{return Z($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw ww.envVar(A,$,`${w} (via ${U.name} parser)`,Y)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,Y]of Object.entries(JJ.env))if(J.startsWith(A)&&Y!==void 0)w[J]=Y;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(Y){J.push(`Cannot parse value "${w}" as ${A}: ${Y}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:Y="text"}=A,U=J||this.generateEnvPrefix($),Z=[];switch(this.extractEnvVarInfo(w,[],U,Z),Y){case"markdown":return this.formatAsMarkdown(Z,$);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,$)}}extractEnvVarInfo($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=`${A}_${Z.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Z,A,J);else J.push({key:B,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Z.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
81
81
|
|
|
82
82
|
`;for(let J of $)A+=`${J.key}
|
|
83
83
|
`,A+=` Type: ${J.type}
|
|
@@ -89,25 +89,25 @@ export type ConfigOf = Config
|
|
|
89
89
|
`;A+=`| Variable | Type | Description | Example |
|
|
90
90
|
`,A+=`|----------|------|-------------|----------|
|
|
91
91
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
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
|
-
${
|
|
92
|
+
`;return A}}function MT($,w){let A=Yj("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function $j($,w,A={}){return wj($,w,A,new WeakMap)}function wj($,w,A,J){let{arrayMergeMode:Y="replace",skipNullish:U=!1,customMerger:Z}=A;if(w===null||w===void 0)return U?$:w;if(Z){let B=Z($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return Aj($,w,Y,J);if(!w0(w)||!w0($))return w;return yT($,w,A,J)}function Aj($,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 IT($,w);case"smart":return CT($,w,J);default:return w}return w}function IT($,w){let A=[...w];for(let J of $)if(!A.some((Y)=>z8(Y,J)))A.push(J);return A}function CT($,w,A){if(w.length===0)return $;if($.length===0)return w;if(w0(w[0])&&w0($[0]))return LT($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}function LT($,w,A){let J=[...w];for(let Y of $){if(!w0(Y)){J.push(Y);continue}let U=["id","name","key","path","type"],Z=!1;for(let B of U)if(B in Y){if(J.find((W)=>w0(W)&&(B in W)&&W[B]===Y[B])){Z=!0;break}}if(!Z)J.push(Y)}return J}function yT($,w,A,J){let Y=w;if(w0(Y)&&J.has(Y))return J.get(Y);let U={...$};if(w0(Y))J.set(Y,U);for(let Z in Y){if(!Object.prototype.hasOwnProperty.call(Y,Z))continue;let B=Y[Z],W=U[Z];if(A.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){U[Z]=B;continue}if(w0(B)&&w0(W))U[Z]=wj(W,B,A,J);else if(Array.isArray(B)||Array.isArray(W))U[Z]=Aj(W,B,A.arrayMergeMode||"smart",J);else U[Z]=B}return U}function X8($,w,A="replace"){return $j($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function z8($,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(!z8($[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 Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!z8($[Y],w[Y]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class xJ{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:Y=!0,cacheTtl:U,trackPerformance:Z=!0,verbose:B=!1}=A;if(Y){let E=$1.getWithFileCheck("file",$);if(E){if(B)console.log(`Configuration loaded from cache: ${$}`);return E}}let W=async()=>{if(!YJ($))return null;try{let E=`?t=${Date.now()}`,j=await import($+E),F=j.default||j,f="default"in j,z=Object.keys(j).length>0;if(!f&&!z)throw new x1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new x1($,Error("Configuration must export a valid object"),"unknown");let H={config:X8(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)$1.setWithFileCheck("file",H,$,U);return H}catch(E){throw E instanceof Error?ww.configLoad($,E):ww.configLoad($,Error(String(E)))}};if(Z)return i1.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let Y=await this.loadFromPath(J,w,A);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(A.verbose)console.warn(`Failed to load config from ${J}:`,Y)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),Y=[];for(let U of J)for(let Z of this.extensions)Y.push(eU(w,`${U}${Z}`));return Y}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 oE(async()=>{return YJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!YJ($))return J;if(w||A){let Y=this.generateNamePatterns(w||"",A);for(let U of Y)for(let Z of this.extensions){let B=eU($,`${U}${Z}`);if(await this.checkFileAccess(B))J.push(B)}}else try{let{readdirSync:Y}=await import("fs"),U=Y($);for(let Z of U)if(this.looksLikeConfigFile(Z)){let B=eU($,Z);if(await this.checkFileAccess(B))J.push(B)}}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(!YJ($))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:Y}=await import("fs"),U=Y($,"utf8");JSON.parse(U)}catch(Y){w.push(`Invalid JSON syntax: ${Y}`)}}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 Y=await this.loadFromPath(J,{},w);if(Y)A.set(J,Y.config)}catch(Y){if(w.verbose)console.warn(`Failed to preload ${J}:`,Y)}})),A}}class _8{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:Y=!0,validateTypes:U=!0,customRules:Z=[],trackPerformance:B=!0,verbose:W=!1}=A,E=async()=>{let j=[],F=[],f={stopOnFirstError:J,validateRequired:Y,validateTypes:U,customRules:Z,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,f);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Z],f);else return this.validateWithJSONSchema($,w,f)}catch(z){return j.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:j,warnings:F}}};if(B)return await i1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!c2(w))throw new P1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),Y=J.default||J;if(Array.isArray(Y))return this.validateWithRules($,Y,A);else return this.validateWithJSONSchema($,Y,A)}catch(J){throw new P1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],Y=[];return this.validateObjectAgainstSchema($,w,"",J,Y,A),{isValid:J.length===0,errors:J,warnings:Y}}validateObjectAgainstSchema($,w,A,J,Y,U){if(U.validateTypes&&w.type){let Z=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(Z)){if(J.push({path:A,message:`Expected type ${B.join(" or ")}, got ${Z}`,expected:B.join(" or "),actual:Z,rule:"type"}),U.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"}),U.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 Z=0;Z<$.length;Z++){let B=A?`${A}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema($[Z],w.items,B,J,Y,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Z=$;if(U.validateRequired&&w.required){for(let B of w.required)if(!(B in Z)){if(J.push({path:A?`${A}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in Z){let E=A?`${A}.${B}`:B;if(this.validateObjectAgainstSchema(Z[B],W,E,J,Y,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(Z))if(!B.has(W))Y.push({path:A?`${A}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],Y=[];for(let U of w)try{let Z=this.getValueByPath($,U.path),B=this.validateWithRule(Z,U,U.path);if(J.push(...B),A.stopOnFirstError&&J.length>0)break}catch(Z){J.push({path:U.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:Y}}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 Y=Array.isArray($)?"array":typeof $;if(Y!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${Y}`,expected:w.type,actual:Y,rule:"type"})}if(w.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:Y,rule:"min"})}if(w.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:Y,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 Y=w.validator($);if(Y)J.push({path:A,message:w.message||Y,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let Y of A)if(J&&typeof J==="object"&&Y in J)J=J[Y];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,Y,U,Z]=J;w.push({path:Y,required:!U,type:this.mapTypeScriptType(Z)})}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:Ej},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class D8{fileLoader=new xJ;envProcessor=new kJ;validator=new _8;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:Y,validate:U,...Z}=$;try{if(A?.enabled){let W=this.checkCache(Z.name||"",Z);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(Z,!0,A)}catch(W){let E=Z.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(E)throw W;B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let j=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),F=!j&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),f=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(E&&(f||j))throw W;if(F&&(!E||!f))B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(Y||U)await this.validateConfiguration(B.config,Y,U,Z.name);if(A?.enabled&&B)this.cacheResult(Z.name||"",B,A,Z);if(J?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:Z.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(W);if(J.slowThreshold&&W.duration>J.slowThreshold)z0.warn(`Slow configuration loading detected: ${W.duration}ms for ${Z.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw z0.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:Y,cwd:U,configDir:Z,defaultConfig:B,checkEnv:W=!0,arrayStrategy:E="replace",verbose:j=!1}=$,F=U||Gw.cwd(),f=[],z=await this.loadLocalConfiguration(J,Y,F,Z,B,E,j,W,A);if(z)return f.push(...this.getLocalSearchPaths(J,Y,F,Z)),this.finalizeResult(z,f,W,J,j);let H=await this.loadHomeConfiguration(J,Y,B,E,j,W);if(H)return f.push(...this.getHomeSearchPaths(J,Y)),this.finalizeResult(H,f,W,J,j);let T=await this.loadPackageJsonConfiguration(J,Y,F,B,E,j,W);if(T)return f.push(k$(F,"package.json")),this.finalizeResult(T,f,W,J,j);if(f.push(...this.getAllSearchPaths(J,Y,F,Z)),w)throw ww.configNotFound(J,f,Y);return{...await this.applyEnvironmentVariables(J,B,W,j),warnings:[`No configuration file found for "${J}"${Y?` or alias "${Y}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,Y,U,Z,B,W){let E=B?D1($,Y,Z):Y,j=this.getLocalDirectories(A,J);for(let F of j){if(Z)z0.info(`Searching for configuration in: ${F}`);let f=this.fileLoader.generateConfigPaths($,F,w),z=await this.fileLoader.tryLoadFromPaths(f,E,{arrayStrategy:U,verbose:Z,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(z){if(Z)z0.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration($,w,A,J,Y,U){if(!$)return null;let Z=U?D1($,A,Y):A,B=[k$(nw(),".config",$),k$(nw(),".config"),nw()];for(let W of B){if(Y)z0.info(`Checking home directory: ${W}`);let E=this.fileLoader.generateConfigPaths($,W,w),j=await this.fileLoader.tryLoadFromPaths(E,Z,{arrayStrategy:J,verbose:Y});if(j){if(Y)z0.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,J,Y,U,Z){let B=Z?D1($,J,U):J;try{let W=k$(A,"package.json");if(!j8(W))return null;let E=await import(W),j=E[$],F=$;if(!j&&w)j=E[w],F=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(U)z0.success(`Configuration loaded from package.json: ${F}`);return{config:X8(B,j,Y),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(U)z0.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}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:D1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let Y=[];if(A){let U=A($);if(U)Y.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)Y.push(...U.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(Y.length>0)throw ww.configValidation(J||"unknown",Y,J)}checkCache($,w){let A=this.generateCacheKey($,w);return $1.get(A)||null}cacheResult($,w,A,J){let Y=this.generateCacheKey($,J);$1.set(Y,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([$,k$($,"config"),k$($,".config"),w?k$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let Y=[];return Y.push(...this.getLocalSearchPaths($,w,A,J)),Y.push(...this.getHomeSearchPaths($,w)),Y.push(k$(A,"package.json")),Y}getLocalSearchPaths($,w,A,J){let Y=this.getLocalDirectories(A,J),U=[];for(let Z of Y)U.push(...this.fileLoader.generateConfigPaths($,Z,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[k$(nw(),".config",$),k$(nw(),".config"),nw()],J=[];for(let Y of A)J.push(...this.fileLoader.generateConfigPaths($,Y,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function yE($){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 VT($){return i0.loadConfig({...$,__strictErrorHandling:!0})}async function Jj($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await i0.loadConfig($);else J=await i0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let Y=J instanceof Error?J.name:"UnknownError",U=J instanceof Error?J.message:String(J);if(!(Y==="ConfigNotFoundError"||Y==="ConfigLoadError"||Y==="ConfigValidationError"||U.includes("config"))&&$.verbose)z0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let Z=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await i0.applyEnvironmentVariables(Z.name||"",w,!0,Z.verbose||!1))?.config??w;return w}}async function ST($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await i0.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"&&yE(A)))return(await i0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await i0.loadConfig({...$,cwd:$.cwd||Gw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&yE(w)))return(await i0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function OT($,w,A="replace"){let J=new xJ;try{let Y=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return Y?Y.config:null}catch{return null}}function D1($,w,A=!1){let J=new kJ,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=[`${Y}_${F.join("_").toUpperCase()}`,`${Y}_${F.map((T)=>T.toUpperCase()).join("")}`,`${Y}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,H;for(let T of f)if(z=Gw.env[T],z!==void 0){H=T;break}if(z!==void 0&&H)if(typeof j==="boolean")W[E]=["true","1","yes"].includes(z.toLowerCase());else if(typeof j==="number"){let T=Number(z);if(!Number.isNaN(T))W[E]=T}else if(Array.isArray(j))try{W[E]=JSON.parse(z)}catch{W[E]=z.split(",").map((T)=>T.trim())}else W[E]=z;else if(j&&typeof j==="object"&&!Array.isArray(j))W[E]=U(j,F)}return W}return U(w)}function XT($){let w=k$(Gw.cwd(),$.configDir),A=k$(Gw.cwd(),$.generatedDir),J=k$(A,"config-types.ts");if(!j8(JE(J)))q2(JE(J),{recursive:!0,mode:511});let Y=j8(w)?K2(w).map((Z)=>Z.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],U=`// Generated by bunfig v${UH}
|
|
93
|
+
export type ConfigNames = ${Y.length?`'${Y.join("' | '")}'`:"string"}
|
|
94
|
+
`;h2(J,U,{mode:438})}function _T($){let w=null,A=null,J=()=>{if(!A)A=Jj($).then((U)=>{return w=U,U},(U)=>{let Z="defaultConfig"in $?$.defaultConfig:{};if(w=Z,"verbose"in $&&$.verbose)z0.warn("Config loading failed, using defaults:",[U instanceof Error?U:Error(String(U))]);return Z});return A},Y="defaultConfig"in $?$.defaultConfig:{};return w=Y,J(),new Proxy({},{get(U,Z){if(w)return w[Z];let B=Y[Z];return J(),B},has(U,Z){return Z in(w||Y)},ownKeys(){return Object.keys(w||Y)},getOwnPropertyDescriptor(U,Z){return Object.getOwnPropertyDescriptor(w||Y,Z)},set(U,Z,B){if(!w)w={...Y};return w[Z]=B,!0}})}function DT($){let w=KE(n2.cwd(),$?.configDir||"./config");function A(){if(!v2(w))return[];let Y=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),U=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Z=m2(w).filter((W)=>Y.has($8(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:E}of Z){let j=$8(E).toLowerCase(),F=B.get(W);if(!F){B.set(W,E);continue}let f=$8(F).toLowerCase();if(U.indexOf(j)<U.indexOf(f))B.set(W,E)}return Array.from(B.entries()).map(([W,E])=>({base:W,file:E})).sort((W,E)=>W.base.localeCompare(E.base))}function J(){let Y=A(),U=Y.map((W)=>W.base),Z=U.length?U.map((W)=>`'${W}'`).join(" | "):"string",B=Y.length?`{
|
|
95
|
+
${Y.map((W)=>{let E=KE(w,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${E}').default`}).join(`,
|
|
96
96
|
`)}
|
|
97
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
98
|
-
export type ConfigByName = ${
|
|
97
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${Z}
|
|
98
|
+
export type ConfigByName = ${B}
|
|
99
99
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
100
100
|
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 T of
|
|
103
|
-
`;if(
|
|
104
|
-
`;if(
|
|
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$()||!
|
|
101
|
+
`}return{name:"bunfig-plugin",setup(Y){Y.onResolve({filter:/^virtual:bunfig-types$/},(U)=>{return{path:U.path,namespace:"bunfig-virtual"}}),Y.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function WH($,w={}){let A=RJ.cwd();while(A.includes("storage"))A=hE(A,"..");let J=hE(A,$||"");if(w?.relative)return g2(RJ.cwd(),J);return J}function F$(){if(P0.env.NODE_ENV==="test"||P0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function EH(){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 fj{async format($){let w=await EH(),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 PJ{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={...SJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new fj,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,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,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{...E8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...E8};return{...E8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:SJ.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,Y=0,U=3,Z=1000;while(Y<U)try{try{try{await a2(this.config.logDirectory,IE.F_OK|IE.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await s2(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:D0.from($);try{if(!UJ(this.currentLogFile))await J8(this.currentLogFile,"",{mode:420});if(J=ME(this.currentLogFile,"a",420),r2(J,B,{flag:"a"}),NE(J),J!==void 0)A8(J),J=void 0;if((await aw(this.currentLogFile)).size===0){if(await J8(this.currentLogFile,B,{flag:"w",mode:420}),(await aw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let E=W;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(Y<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${U}:`,j);let F=Z*2**Y;await new Promise((f)=>setTimeout(f,F)),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(J!==void 0)try{A8(J)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(Y===U-1){let E=B,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),B}Y++;let W=Z*2**(Y-1);await new Promise((E)=>setTimeout(E,W))}})();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 sw(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 sw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return sw(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(([,Z],[,B])=>B.createdAt.getTime()-Z.createdAt.getTime()),Y=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,Y);if(J.length>U)for(let[Z]of J.slice(U))this.encryptionKeys.delete(Z),this.keys.delete(Z)}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),J=l2("aes-256-gcm",w,A),Y=D0.isBuffer($)?$:D0.from($,"utf8"),U=J.update(Y),Z=J.final(),B=U.length+Z.length,W=J.getAuthTag(),E=D0.allocUnsafe(16+B+16);return A.copy(E,0),U.copy(E,16),Z.copy(E,16+U.length),W.copy(E,16+B),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=LE(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(D0.from(D0.concat(Y)))),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 aw(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 Y=await ZJ(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await aw(A).catch(()=>null))try{if(await CE(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await WJ(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await J8(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await aw(A).catch(()=>null))await CE(A,U)}if(this.currentLogFile=J,w.maxFiles){let Y=(await ZJ(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Z)=>Z.localeCompare(U));for(let U of Y.slice(w.maxFiles))await WJ(sw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=RE($),J=t2(w),Y=LE();await $T(A,Y,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()})),UJ(this.currentLogFile))try{let $=ME(this.currentLogFile,"r+");NE($),A8($)}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 ZJ(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await WJ(sw(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 m.env.NO_COLOR<"u",w=m.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof m.stderr<"u"&&m.stderr.isTTY||typeof m.stdout<"u"&&m.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=m.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${b.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,Y)=>{let U=b.underline(b.blue(J)),Z=this.toAbsoluteFilePath(Y);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(Z)}`,W="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${B}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),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 $=m.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=m.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(o2(w)||w.startsWith("./")||w.startsWith("../"))w=e2(w);else return null;return UJ(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,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);let{consoleText:W,fileText:E}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":GH[$],f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:b.gray(W),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:b.green(W),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.error(z),B){let H=B.split(`
|
|
102
|
+
`);for(let T of H)if(T.trim()&&!T.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:b.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!F$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}let j=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
103
|
+
`;if(B)j+=`${B}
|
|
104
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(Y,U)=>{},finish:(Y)=>{},interrupt:(Y,U)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!F$()&&m.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Y,U)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Y),this.activeProgressBar.total),U!==void 0)this.activeProgressBar.message=U;if(this.shouldStyleConsole()&&!F$()&&m.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Y)},interrupt:(Y,U="info")=>{if(!F$()&&m.stdout.isTTY)m.stdout.write(`
|
|
105
|
+
`);if(this[U==="warning"?"warn":U](Y),this.activeProgressBar&&this.shouldStyleConsole()&&!F$()&&m.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)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:A,message:`${b.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),W=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)W+=` ${JSON.stringify(A)}`;if(W+=`
|
|
106
|
+
`,W=W.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:B,icon:this.options.showIcons===!1?"":b.green("✓"),tag:E,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F$())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=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 PJ(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(!UJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return RE(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=D0.isBuffer($)?$:D0.from($,"base64"),Y=J.subarray(0,16),U=J.subarray(J.length-16),Z=J.subarray(16,J.length-16),B=p2("aes-256-gcm",A,Y);B.setAuthTag(U);let W=B.update(Z),E=B.final(),j=W.length+E.length,F=D0.allocUnsafe(j);return W.copy(F,0),E.copy(F,W.length),F.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 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),J=this.formatFileTimestamp(w),{consoleText:Y,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=Y.split(`
|
|
107
|
+
`),W=Math.max(...B.map((f)=>f.length))+2,E=`┌${"─".repeat(W)}┐`,j=`└${"─".repeat(W)}┘`,F=B.map((f)=>{return this.formatConsoleMessage({timestamp:A,message:b.cyan(f),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(E),showTimestamp:!1})),F.forEach((f)=>console.error(f)),console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(j),showTimestamp:!1}))}else if(!F$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${J} ${this.environment}.INFO: [BOX] ${U}
|
|
108
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(F$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.toString().trim().toLowerCase();m.stdin.removeListener("data",A);try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!1)}catch{}m.stdin.pause(),console.error(""),w(Y==="y"||Y==="yes")};try{if(typeof m.stdin.setRawMode==="function")m.stdin.setRawMode(!0)}catch{}m.stdin.resume(),m.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 Z=/%([sdijfo%])/g,B=0;if(A=$.replace(Z,(W,E)=>{if(E==="%")return"%";if(B>=w.length)return W;let j=w[B++];switch(E){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 W}}),B<w.length)A+=` ${w.slice(B).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:J,fileText:Y}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${B}${Z} ${b.cyan(J)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
109
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!m.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=b.green("━".repeat(J)),Z=b.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?b.green("✓"):b.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=m.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,m.stdout.write($.lastRenderedLine),w)m.stdout.write(`
|
|
110
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!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(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await ZJ(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=sw(this.config.logDirectory,J);if($.before)try{if((await aw(Y)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${Y}:`,U);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 WJ(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function TH($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:Y=()=>!0,fallback:U}=w,Z=Error("Unknown error occurred");for(let B=0;B<=A;B++)try{return await $()}catch(W){if(Z=W instanceof Error?W:Error(String(W)),B===A||!Y(Z))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}class k8{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:J,useCamelCase:Y=!0,useBackwardCompatibility:U=!0,customParsers:Z={},verbose:B=!1,trackPerformance:W=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],j,{useCamelCase:Y,useBackwardCompatibility:U,customParsers:Z,verbose:B,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return L8.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=Z.map((j)=>this.formatEnvKey(j,J.useCamelCase)),W=`${A}_${B.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Z.map((j)=>j.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Z,A,J);else{let j=BJ.env[W]||(E?BJ.env[E]:void 0);if(j!==void 0){if(J.verbose){let F=BJ.env[W]?W:E}try{$[Y]=this.parseEnvironmentValue(j,typeof U,W,J.customParsers,J.configName)}catch(F){if(F instanceof Q8)throw F;throw w1.envVar(W,j,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,Y){for(let[U,Z]of Object.entries(J))try{return Z($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw w1.envVar(A,$,`${w} (via ${U.name} parser)`,Y)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,Y]of Object.entries(BJ.env))if(J.startsWith(A)&&Y!==void 0)w[J]=Y;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(Y){J.push(`Cannot parse value "${w}" as ${A}: ${Y}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:Y="text"}=A,U=J||this.generateEnvPrefix($),Z=[];switch(this.extractEnvVarInfo(w,[],U,Z),Y){case"markdown":return this.formatAsMarkdown(Z,$);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,$)}}extractEnvVarInfo($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=`${A}_${Z.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Z,A,J);else J.push({key:B,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Z.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
111
111
|
|
|
112
112
|
`;for(let J of $)A+=`${J.key}
|
|
113
113
|
`,A+=` Type: ${J.type}
|
|
@@ -119,30 +119,30 @@ export type ConfigOf = Config
|
|
|
119
119
|
`;A+=`| Variable | Type | Description | Example |
|
|
120
120
|
`,A+=`|----------|------|-------------|----------|
|
|
121
121
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
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: ${J.message}`);throw
|
|
122
|
+
`;return A}}function HH($,w,A={}){return Nj($,w,A,new WeakMap)}function Nj($,w,A,J){let{arrayMergeMode:Y="replace",skipNullish:U=!1,customMerger:Z}=A;if(w===null||w===void 0)return U?$:w;if(Z){let B=Z($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return Mj($,w,Y,J);if(!A0(w)||!A0($))return w;return RH($,w,A,J)}function Mj($,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 qH($,w);case"smart":return KH($,w,J);default:return w}return w}function qH($,w){let A=[...w];for(let J of $)if(!A.some((Y)=>N8(Y,J)))A.push(J);return A}function KH($,w,A){if(w.length===0)return $;if($.length===0)return w;if(A0(w[0])&&A0($[0]))return hH($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}function hH($,w,A){let J=[...w];for(let Y of $){if(!A0(Y)){J.push(Y);continue}let U=["id","name","key","path","type"],Z=!1;for(let B of U)if(B in Y){if(J.find((W)=>A0(W)&&(B in W)&&W[B]===Y[B])){Z=!0;break}}if(!Z)J.push(Y)}return J}function RH($,w,A,J){let Y=w;if(A0(Y)&&J.has(Y))return J.get(Y);let U={...$};if(A0(Y))J.set(Y,U);for(let Z in Y){if(!Object.prototype.hasOwnProperty.call(Y,Z))continue;let B=Y[Z],W=U[Z];if(A.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){U[Z]=B;continue}if(A0(B)&&A0(W))U[Z]=Nj(W,B,A,J);else if(Array.isArray(B)||Array.isArray(W))U[Z]=Mj(W,B,A.arrayMergeMode||"smart",J);else U[Z]=B}return U}function Ij($,w,A="replace"){return HH($,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(A0($)&&A0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!N8($[Y],w[Y]))return!1}return!0}return!1}function A0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Cj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:Y=!0,cacheTtl:U,trackPerformance:Z=!0,verbose:B=!1}=A;if(Y){let E=NJ.getWithFileCheck("file",$);if(E){if(B)console.log(`Configuration loaded from cache: ${$}`);return E}}let W=async()=>{if(!EJ($))return null;try{let E=`?t=${Date.now()}`,j=await import($+E),F=j.default||j,f="default"in j,z=Object.keys(j).length>0;if(!f&&!z)throw new OJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new OJ($,Error("Configuration must export a valid object"),"unknown");let H={config:Ij(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)NJ.setWithFileCheck("file",H,$,U);return H}catch(E){throw E instanceof Error?w1.configLoad($,E):w1.configLoad($,Error(String(E)))}};if(Z)return L8.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let Y=await this.loadFromPath(J,w,A);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(A.verbose)console.warn(`Failed to load config from ${J}:`,Y)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),Y=[];for(let U of J)for(let Z of this.extensions)Y.push(Y8(w,`${U}${Z}`));return Y}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 U of J){if(!U)continue;if(A.push(U,`.${U}.config`,`${U}.config`,`.${U}`),$)A.push(`${$}.${U}.config`,`.${$}.${U}.config`)}let Y=new Set;return A.filter((U)=>{if(!U||Y.has(U))return!1;return Y.add(U),!0})}checkFileAccess($){return TH(async()=>{return EJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!EJ($))return J;if(w||A){let Y=this.generateNamePatterns(w||"",A);for(let U of Y)for(let Z of this.extensions){let B=Y8($,`${U}${Z}`);if(await this.checkFileAccess(B))J.push(B)}}else try{let{readdirSync:Y}=await import("fs"),U=Y($);for(let Z of U)if(this.looksLikeConfigFile(Z)){let B=Y8($,Z);if(await this.checkFileAccess(B))J.push(B)}}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(!EJ($))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:Y}=await import("fs"),U=Y($,"utf8");JSON.parse(U)}catch(Y){w.push(`Invalid JSON syntax: ${Y}`)}}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 Y=await this.loadFromPath(J,{},w);if(Y)A.set(J,Y.config)}catch(Y){if(w.verbose)console.warn(`Failed to preload ${J}:`,Y)}})),A}}class Lj{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:Y=!0,validateTypes:U=!0,customRules:Z=[],trackPerformance:B=!0,verbose:W=!1}=A,E=async()=>{let j=[],F=[],f={stopOnFirstError:J,validateRequired:Y,validateTypes:U,customRules:Z,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,f);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Z],f);else return this.validateWithJSONSchema($,w,f)}catch(z){return j.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:j,warnings:F}}};if(B)return await L8.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!wT(w))throw new XJ(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),Y=J.default||J;if(Array.isArray(Y))return this.validateWithRules($,Y,A);else return this.validateWithJSONSchema($,Y,A)}catch(J){throw new XJ(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],Y=[];return this.validateObjectAgainstSchema($,w,"",J,Y,A),{isValid:J.length===0,errors:J,warnings:Y}}validateObjectAgainstSchema($,w,A,J,Y,U){if(U.validateTypes&&w.type){let Z=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(Z)){if(J.push({path:A,message:`Expected type ${B.join(" or ")}, got ${Z}`,expected:B.join(" or "),actual:Z,rule:"type"}),U.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"}),U.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 Z=0;Z<$.length;Z++){let B=A?`${A}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema($[Z],w.items,B,J,Y,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Z=$;if(U.validateRequired&&w.required){for(let B of w.required)if(!(B in Z)){if(J.push({path:A?`${A}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in Z){let E=A?`${A}.${B}`:B;if(this.validateObjectAgainstSchema(Z[B],W,E,J,Y,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(Z))if(!B.has(W))Y.push({path:A?`${A}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],Y=[];for(let U of w)try{let Z=this.getValueByPath($,U.path),B=this.validateWithRule(Z,U,U.path);if(J.push(...B),A.stopOnFirstError&&J.length>0)break}catch(Z){J.push({path:U.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:Y}}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 Y=Array.isArray($)?"array":typeof $;if(Y!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${Y}`,expected:w.type,actual:Y,rule:"type"})}if(w.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:Y,rule:"min"})}if(w.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:Y,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 Y=w.validator($);if(Y)J.push({path:A,message:w.message||Y,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let Y of A)if(J&&typeof J==="object"&&Y in J)J=J[Y];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,Y,U,Z]=J;w.push({path:Y,required:!U,type:this.mapTypeScriptType(Z)})}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:NH},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function MH($){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 yj{fileLoader=new Cj;envProcessor=new k8;validator=new Lj;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:Y,validate:U,...Z}=$;try{if(A?.enabled){let W=this.checkCache(Z.name||"",Z);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(Z,!0,A)}catch(W){let E=Z.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(E)throw W;B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let j=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),F=!j&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),f=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(E&&(f||j))throw W;if(F&&(!E||!f))B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(Y||U)await this.validateConfiguration(B.config,Y,U,Z.name);if(A?.enabled&&B)this.cacheResult(Z.name||"",B,A,Z);if(J?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:Z.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(W);if(J.slowThreshold&&W.duration>J.slowThreshold)Q0.warn(`Slow configuration loading detected: ${W.duration}ms for ${Z.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw Q0.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:Y,cwd:U,configDir:Z,defaultConfig:B,checkEnv:W=!0,arrayStrategy:E="replace",verbose:j=!1}=$,F=U||QJ.cwd(),f=[],z=await this.loadLocalConfiguration(J,Y,F,Z,B,E,j,W,A);if(z)return f.push(...this.getLocalSearchPaths(J,Y,F,Z)),this.finalizeResult(z,f,W,J,j);let H=await this.loadHomeConfiguration(J,Y,B,E,j,W);if(H)return f.push(...this.getHomeSearchPaths(J,Y)),this.finalizeResult(H,f,W,J,j);let T=await this.loadPackageJsonConfiguration(J,Y,F,B,E,j,W);if(T)return f.push($0(F,"package.json")),this.finalizeResult(T,f,W,J,j);if(f.push(...this.getAllSearchPaths(J,Y,F,Z)),w)throw w1.configNotFound(J,f,Y);return{...await this.applyEnvironmentVariables(J,B,W,j),warnings:[`No configuration file found for "${J}"${MH(Y)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,Y,U,Z,B,W){let E=B?FJ($,Y,Z):Y,j=this.getLocalDirectories(A,J);for(let F of j){if(Z)Q0.info(`Searching for configuration in: ${F}`);let f=this.fileLoader.generateConfigPaths($,F,w),z=await this.fileLoader.tryLoadFromPaths(f,E,{arrayStrategy:U,verbose:Z,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(z){if(Z)Q0.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration($,w,A,J,Y,U){if(!$)return null;let Z=U?FJ($,A,Y):A,B=[$0(mw(),".config",$),$0(mw(),".config"),mw()];for(let W of B){if(Y)Q0.info(`Checking home directory: ${W}`);let E=this.fileLoader.generateConfigPaths($,W,w),j=await this.fileLoader.tryLoadFromPaths(E,Z,{arrayStrategy:J,verbose:Y});if(j){if(Y)Q0.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,J,Y,U,Z){let B=Z?FJ($,J,U):J;try{let W=$0(A,"package.json");if(!T2(W))return null;let E={};try{E=JSON.parse(H2(W,"utf8"))}catch(f){if(U)Q0.warn("Failed to parse package.json:",[f instanceof Error?f:Error(String(f))]);return null}let j=E[$],F=$;if(!j&&w){let f=Array.isArray(w)?w:[w];for(let z of f){if(!z)continue;if(E[z]){j=E[z],F=z;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(U)Q0.success(`Configuration loaded from package.json: ${F}`);return{config:Ij(B,j,Y),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(U)Q0.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}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:FJ($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let Y=[];if(A){let U=A($);if(U)Y.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)Y.push(...U.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(Y.length>0)throw w1.configValidation(J||"unknown",Y,J)}checkCache($,w){let A=this.generateCacheKey($,w);return NJ.get(A)||null}cacheResult($,w,A,J){let Y=this.generateCacheKey($,J);NJ.set(Y,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([$,$0($,"config"),$0($,".config"),w?$0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,J){let Y=[];return Y.push(...this.getLocalSearchPaths($,w,A,J)),Y.push(...this.getHomeSearchPaths($,w)),Y.push($0(A,"package.json")),Y}getLocalSearchPaths($,w,A,J){let Y=this.getLocalDirectories(A,J),U=[];for(let Z of Y)U.push(...this.fileLoader.generateConfigPaths($,Z,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[$0(mw(),".config",$),$0(mw(),".config"),mw()],J=[];for(let Y of A)J.push(...this.fileLoader.generateConfigPaths($,Y,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function FJ($,w,A=!1){let J=new k8,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=[`${Y}_${F.join("_").toUpperCase()}`,`${Y}_${F.map((T)=>T.toUpperCase()).join("")}`,`${Y}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,H;for(let T of f)if(z=QJ.env[T],z!==void 0){H=T;break}if(z!==void 0&&H)if(typeof j==="boolean")W[E]=["true","1","yes"].includes(z.toLowerCase());else if(typeof j==="number"){let T=Number(z);if(!Number.isNaN(T))W[E]=T}else if(Array.isArray(j))try{W[E]=JSON.parse(z)}catch{W[E]=z.split(",").map((T)=>T.trim())}else W[E]=z;else if(j&&typeof j==="object"&&!Array.isArray(j))W[E]=U(j,F)}return W}return U(w)}function M8($,w){let A=[];function J(Y){let U;try{U=uE.readdirSync(Y)}catch{return}for(let Z of U){let B=F0.join(Y,Z);try{if(uE.statSync(B).isDirectory())J(B);else if(Z===w)A.push(Y)}catch{continue}}}return J($),A}function C($,w,A){if(A||Y$.verbose)console.debug(`[tlsx:${$}] ${w}`)}function Oj(){return Sj.env.SUDO_PASSWORD}function OH($){let w=$.toLowerCase();return VH.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function _J($){if(Array.isArray($))return $.map((A)=>_J(A));if(typeof $==="string")return SH.test($)?cE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(OH(A)){w[A]=cE;continue}w[A]=_J(J)}return w}function bJ($){return JSON.stringify(_J($))}function XH($){let w=Oj();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 $w($,w={}){let A=XH($);try{let{stdout:J,stderr:Y}=await yH(A,{cwd:w.cwd||Sj.cwd(),timeout:w.timeout||30000});return{stdout:J.trim(),stderr:Y.trim()}}catch(J){let Y=Error(`Failed to execute command: ${$}
|
|
123
|
+
Error: ${J.message}`);throw Y.stack=J.stack,Y}}function Xj($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function x8($){let w=F0.join(CH.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:Y$.basePath&&Y$.basePath.trim()!==""?Y$.basePath:w,J=$.certPath?F0.isAbsolute($.certPath)?$.certPath:F0.join(A,$.certPath):F0.join(A,Y$.certPath),Y=$.keyPath?F0.isAbsolute($.keyPath)?$.keyPath:F0.join(A,$.keyPath):F0.join(A,Y$.keyPath),U=$.caCertPath?F0.isAbsolute($.caCertPath)?$.caCertPath:F0.join(A,$.caCertPath):F0.join(A,Y$.caCertPath);return{certPath:J,keyPath:Y,caCertPath:U,basePath:A}}function _j($){let w=[],A=new Set;if($.domain)A.add($.domain);if($.domains?.length)$.domains.forEach((J)=>A.add(J));for(let J of A)w.push({type:2,value:J});if($.altNameIPs?.length)for(let J of $.altNameIPs)w.push({type:7,ip:J});if($.altNameURIs?.length)for(let J of $.altNameURIs)w.push({type:6,value:J});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return C(L.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function P8($){let w=$.notBeforeDays??f0.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:f0.DEFAULT_VALIDITY_DAYS);C(L.CERT,"Calculating certificate validity dates",$.verbose);let J=new Date(Date.now()-86400*w*1000),Y=new Date(J.getTime()+A*24*60*60*1000);return J.setUTCHours(0,0,0,0),Y.setUTCHours(23,59,59,999),C(L.CERT,`Validity period: ${J.toISOString()} to ${Y.toISOString()}`,$.verbose),{notBefore:J,notAfter:Y}}function Q1($){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 r$($,w){let A=Q1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function b1($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let J=2;J<w.length;J++){let Y=w[J],U=[];U.unshift(Y&127),Y>>=7;while(Y>0)U.unshift(Y&127|128),Y>>=7;A.push(...U)}return r$(G0.OID,Buffer.from(A))}function I8($){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 r$(G0.INTEGER,w)}function Dj($,w=0){return r$(G0.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function Qj($){return r$(G0.OCTET_STRING,$)}function t$(...$){return r$(G0.SEQUENCE,Buffer.concat($))}function _H(...$){return r$(G0.SET,Buffer.concat($))}function DH($){return r$(G0.PRINTABLE_STRING,Buffer.from($,"ascii"))}function QH($){return r$(G0.UTF8_STRING,Buffer.from($,"utf8"))}function kH(){return Buffer.from([G0.NULL,0])}function vE($,w,A=!0){let J=160|$|(A?0:0),Y=Q1(w.length);return Buffer.concat([Buffer.from([J]),Y,w])}function mE($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return r$(G0.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),J=($.getUTCMonth()+1).toString().padStart(2,"0"),Y=$.getUTCDate().toString().padStart(2,"0"),U=$.getUTCHours().toString().padStart(2,"0"),Z=$.getUTCMinutes().toString().padStart(2,"0"),B=$.getUTCSeconds().toString().padStart(2,"0"),W=`${A}${J}${Y}${U}${Z}${B}Z`;return r$(G0.UTC_TIME,Buffer.from(W,"ascii"))}}function xH($,w){return t$(mE($),mE(w))}function nE($){let w=[];for(let A of $){let J;switch(A.shortName){case"CN":J=x$.COMMON_NAME;break;case"C":J=x$.COUNTRY;break;case"L":J=x$.LOCALITY;break;case"ST":J=x$.STATE;break;case"O":J=x$.ORGANIZATION;break;case"OU":J=x$.ORGANIZATIONAL_UNIT;break;default:continue}let Y=A.shortName==="C"?DH(A.value):QH(A.value),U=t$(b1(J),Y);w.push(_H(U))}return t$(...w)}function kj($){return t$(b1($),kH())}function PH($){return $.export({type:"spki",format:"der"})}function bH($){if($.includes(":")){let w=$;if($.includes("::")){let Y=$.split("::"),U=Y[0]?Y[0].split(":"):[],Z=Y[1]?Y[1].split(":"):[],B=8-U.length-Z.length,W=Array.from({length:B},()=>"0");w=[...U,...W,...Z].join(":")}let A=w.split(":"),J=Buffer.alloc(16);for(let Y=0;Y<8;Y++){let U=Number.parseInt(A[Y]||"0",16);J.writeUInt16BE(U,Y*2)}return J}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function iH($){let w=[];for(let A of $)if(A.type===2&&A.value){let J=Q1(A.value.length);w.push(Buffer.concat([Buffer.from([130]),J,Buffer.from(A.value,"ascii")]))}else if(A.type===7&&A.ip){let J=bH(A.ip),Y=Q1(J.length);w.push(Buffer.concat([Buffer.from([135]),Y,J]))}else if(A.type===6&&A.value){let J=Q1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),J,Buffer.from(A.value,"ascii")]))}return t$(...w)}function uH($,w){if($){if(w!==void 0)return t$(r$(1,Buffer.from([255])),I8(w));return t$(r$(1,Buffer.from([255])))}return t$()}function cH($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let A=0,J=w;while(J>0&&(J&1)===0)A++,J>>=1;if(w===0)A=7;return Dj(Buffer.from([w]),A)}function vH($){let w=[];if($.serverAuth)w.push(b1(x$.SERVER_AUTH));if($.clientAuth)w.push(b1(x$.CLIENT_AUTH));return t$(...w)}function _1($,w,A){let J=[b1($)];if(w)J.push(r$(1,Buffer.from([255])));return J.push(Qj(A)),t$(...J)}function mH($){let w=[];if(w.push(vE(0,I8(2))),w.push(I8($.serialNumber)),w.push(kj(x$.SHA256_WITH_RSA)),w.push(nE($.issuer)),w.push(xH($.notBefore,$.notAfter)),w.push(nE($.subject)),w.push(PH($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(_1(x$.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,uH($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(_1(x$.KEY_USAGE,$.extensions.keyUsage.critical??!0,cH($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(_1(x$.EXTENDED_KEY_USAGE,!1,vH($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(_1(x$.SUBJECT_ALT_NAME,!1,iH($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(_1(x$.SUBJECT_KEY_IDENTIFIER,!1,Qj($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push(vE(3,t$(...A)))}return t$(...w)}function nH($,w){let A=A1.createSign("SHA256");A.update($);let J=A.sign(w);return t$($,kj(x$.SHA256_WITH_RSA),Dj(J))}function dH($,w){let A=$.toString("base64"),J=[];for(let Y=0;Y<A.length;Y+=64)J.push(A.slice(Y,Y+64));return`-----BEGIN ${w}-----
|
|
124
124
|
${J.join(`
|
|
125
125
|
`)}
|
|
126
126
|
-----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
|
-
`,
|
|
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 T of
|
|
138
|
-
`;if(
|
|
139
|
-
`;if(
|
|
140
|
-
`);if(this[
|
|
141
|
-
`,
|
|
142
|
-
`),
|
|
143
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
144
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
145
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
127
|
+
`}function b8(){return A1.randomBytes(20)}function xj($=2048){let{privateKey:w,publicKey:A}=A1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function gH($){let w=$.export({type:"spki",format:"der"});return A1.createHash("sha1").update(w).digest()}function Pj($){let w={serialNumber:$.serialNumber||b8(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:gH($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=mH(w),J=nH(A,$.signingKey);return{certificate:dH(J,"CERTIFICATE"),certificateDer:J}}function bj($){return $.export({type:"pkcs8",format:"pem"})}function lH($){return A1.createPrivateKey($)}function pH($){let w=new A1.X509Certificate($),A=w.publicKey,J=[],Y=w.subject.split(`
|
|
128
|
+
`);for(let U of Y){let[Z,...B]=U.split("="),W=B.join("=");if(Z&&W)J.push({shortName:Z.trim(),value:W.trim()})}return{publicKey:A,subject:J}}async function i8($={}){C("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||f0.DEFAULT_KEY_SIZE;C("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=xj(w),Y=[{shortName:"C",value:$.countryName||Y$.countryName},{shortName:"ST",value:$.stateName||Y$.stateName},{shortName:"L",value:$.localityName||Y$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:U,notAfter:Z}=P8({validityYears:$.validityYears||f0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:B}=Pj({serialNumber:b8(),notBefore:U,notAfter:Z,subject:Y,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:B,privateKey:bj(A),notBefore:U,notAfter:Z}}async function u8($){if(C("ca","Generating new certificate",$.verbose),C("ca",`Options: ${bJ($)}`,$.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}=pH($.rootCA.certificate),A=lH($.rootCA.privateKey);C("ca",`Generating ${f0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=f0.DEFAULT_KEY_SIZE,{privateKey:Y,publicKey:U}=xj(J),Z=$.commonName||Xj($),B=$.certificateAttributes||[{shortName:"C",value:$.countryName||Y$.countryName},{shortName:"ST",value:$.stateName||Y$.stateName},{shortName:"L",value:$.localityName||Y$.localityName},{shortName:"O",value:$.organizationName||Y$.organizationName},{shortName:"CN",value:Z}],{notBefore:W,notAfter:E}=P8({validityDays:$.validityDays||f0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),j=_j($),F=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},f=$.extKeyUsage||{serverAuth:!0},{certificate:z}=Pj({serialNumber:b8(),notBefore:W,notAfter:E,subject:B,issuer:w,publicKey:U,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:F,extendedKeyUsage:f,subjectAltName:j});return{certificate:z,privateKey:bj(Y),notBefore:W,notAfter:E}}function ij($,w){C(L.STORAGE,`Storing certificate and private key with options: ${bJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=x8({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});C(L.STORAGE,`Certificate path: ${A}`,w?.verbose),C(L.STORAGE,`Private key path: ${J}`,w?.verbose);let Y=C8.dirname(A);if(!b0.existsSync(Y))C(L.STORAGE,`Creating certificate directory: ${Y}`,w?.verbose),b0.mkdirSync(Y,{recursive:!0});C(L.STORAGE,"Writing certificate file",w?.verbose),b0.writeFileSync(A,$.certificate);let U=C8.dirname(J);if(!b0.existsSync(U))C(L.STORAGE,`Creating private key directory: ${U}`,w?.verbose),b0.mkdirSync(U,{recursive:!0});return C(L.STORAGE,"Writing private key file",w?.verbose),b0.writeFileSync(J,$.privateKey),C(L.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function uj($,w){C(L.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=x8({basePath:w?.basePath,caCertPath:w?.caCertPath});C(L.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=C8.dirname(A);if(!b0.existsSync(J))C(L.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),b0.mkdirSync(J,{recursive:!0});return C(L.STORAGE,"Writing CA certificate file",w?.verbose),b0.writeFileSync(A,$),C(L.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function tH($,w){if(DJ.platform()!=="darwin")return!1;try{let A=dE(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return C(L.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(dE("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return C(L.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return C(L.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return C(L.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function c8($,w,A){C(L.TRUST,`Adding certificate to system trust store with options: ${bJ(A)}`,A?.verbose),C(L.TRUST,"Storing certificate and private key",A?.verbose);let J=ij($,A);C(L.TRUST,"Storing CA certificate",A?.verbose);let Y=uj(w,A),U=DJ.platform();C(L.TRUST,`Detected platform: ${U}`,A?.verbose);let Z=oH[U];if(!Z){let B=`Unsupported platform: ${U}`;throw C(L.TRUST,`Error: ${B}`,A?.verbose),Error(B)}return await Z.addCertificate(Y,A),C(L.TRUST,"Certificate successfully added to system trust store",A?.verbose),J}var wR,NJ,L8,AT,JT=($)=>$,UT=($,w)=>{for(var A in w)AT($,A,{get:w[A],enumerable:!0,configurable:!0,set:YT.bind(w,A)})},ZT=($,w)=>()=>($&&(w=$($=0)),w),rE,Yj,$1,i1,Uj,QT,kT,VE,fJ,f8,C$,l,xT,SE,PT,OE,bT,iT,U8,uT,XE,_E,Z8,cT,vT,mT,nT,GJ,Zj,dT,L$,gT,lT,DE,TJ,G8,j$,Q,pT,QE,tT,kE,rT,aT,W8,sT,xE,PE,oT,B8,eT,$H,wH,AH,JH,HJ,Wj,YH,UH="0.15.6",p$,yJ,x1,T8,H8,VJ,q8,K8,P1,h8,R8,ww,Bj,Ej,z0,i0,jj,Fj,ZH,BH,zj,SJ,yN,q$,b,VN,jH,SN,FH,ON,XN,bE,_N,zH,fH,DN,iE,QN,kN,xN,PN,bN,E8,GH,iN,T0,Gj,OJ,Tj,Hj,Q8,qj,Kj,XJ,hj,Rj,w1,NH,Q0,uN,cN,vN,Vj,Y$,f0,L,ew,yH,cE="[redacted]",VH,SH,G0,x$,rH,aH,sH,oH;var cj=h$(()=>{wR=G2(import.meta.url);NJ=new pE,L8=new tE,AT=Object.defineProperty;rE={};UT(rE,{withErrorRecovery:()=>oE,tryLoadConfig:()=>OT,loadConfigWithResult:()=>VT,loadConfig:()=>Jj,isRetryableError:()=>NT,isConfigNotFoundError:()=>RT,isBunfigError:()=>eE,globalPerformanceMonitor:()=>i1,globalCache:()=>$1,getEnvOrDefault:()=>MT,generateConfigTypes:()=>XT,defaultGeneratedDir:()=>Fj,defaultConfigDir:()=>jj,deepMergeWithArrayStrategy:()=>X8,deepMerge:()=>$j,createLibraryConfig:()=>_T,config:()=>ST,bunfigPlugin:()=>DT,applyEnvVarsToConfig:()=>D1,TypeGenerationError:()=>K8,SchemaValidationError:()=>P1,PluginError:()=>R8,PerformanceMonitor:()=>V8,FileSystemError:()=>q8,ErrorFactory:()=>ww,EnvVarError:()=>VJ,EnvProcessor:()=>kJ,ConfigValidator:()=>_8,ConfigValidationError:()=>T8,ConfigNotFoundError:()=>yJ,ConfigMergeError:()=>H8,ConfigLoader:()=>D8,ConfigLoadError:()=>x1,ConfigFileLoader:()=>xJ,ConfigCache:()=>y8,CacheUtils:()=>Uj,BunfigError:()=>p$,BrowserConfigError:()=>h8,ArrayMergeStrategies:()=>Bj});ZH=ZT(async()=>{Yj=import.meta.require,$1=new y8,i1=new V8,Uj={createKey:WT,isEquivalent:BT,estimateMemoryUsage:ET},QT=hJ(F8.cwd(),"config"),kT=hJ(F8.cwd(),"src/generated"),VE=KJ.env.CLARITY_LOG_DIR||M2(zT(),"logs"),fJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:VE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},f8=await fT(),C$={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=C$,xT=C$.red,SE=C$.green,PT=C$.yellow,OE=C$.blue,bT=C$.magenta,iT=C$.cyan,U8=C$.white,uT=C$.gray,XE=C$.bgRed,_E=C$.bgYellow,Z8=C$.bold,cT=C$.dim,vT=C$.italic,mT=C$.underline,nT=C$.reset,GJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Zj={debug:"\uD83D\uDD0D",info:OE("ℹ"),success:SE("✓"),warning:_E(U8(Z8(" WARN "))),error:XE(U8(Z8(" ERROR ")))},dT=new IJ("stacks"),L$=new IJ("bunfig",{showTags:!0}),gT=Q$(k1.cwd(),"config"),lT=Q$(k1.cwd(),"src/generated"),DE=qJ.env.CLARITY_LOG_DIR||R2(qT(),"logs"),TJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:DE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},G8=await KT(),j$={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=j$,pT=j$.red,QE=j$.green,tT=j$.yellow,kE=j$.blue,rT=j$.magenta,aT=j$.cyan,W8=j$.white,sT=j$.gray,xE=j$.bgRed,PE=j$.bgYellow,oT=j$.bgGray,B8=j$.bold,eT=j$.dim,$H=j$.italic,wH=j$.underline,AH=j$.strikethrough,JH=j$.reset,HJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Wj={debug:"\uD83D\uDD0D",info:kE("ℹ"),success:QE("✓"),warning:PE(W8(B8(" WARN "))),error:xE(W8(B8(" ERROR ")))},YH=new LJ("stacks"),p$=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}${$}`}},yJ=class extends p${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})}},x1=class extends p${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}},T8=class extends p${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},H8=class extends p${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}},VJ=class extends p${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})}},q8=class extends p${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}},K8=class extends p${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}},P1=class extends p${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},h8=class extends p${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},R8=class extends p${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}},ww={configNotFound($,w,A){return new yJ($,w,A)},configLoad($,w,A){return new x1($,w,A)},configValidation($,w,A){return new T8($,w,A)},configMerge($,w,A,J){return new H8($,w,A,J)},envVar($,w,A,J){return new VJ($,w,A,J)},fileSystem($,w,A){return new q8($,w,A)},typeGeneration($,w,A){return new K8($,w,A)},schemaValidation($,w,A){return new P1($,w,A)},browserConfig($,w,A,J){return new h8($,w,A,J)},plugin($,w,A){return new R8($,w,A)}},Bj={replace:"replace",concat:"concat",smart:"smart"},Ej=/^https?:\/\//,z0=new LJ("bunfig",{showTags:!0}),i0=new D8,jj=k$(Gw.cwd(),"config"),Fj=k$(Gw.cwd(),"src/generated")});BH=RJ.env.CLARITY_LOG_DIR||d2(WH(),"logs"),zj={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},SJ={...zj},yN=(async()=>{try{let{loadConfig:$}=await ZH().then(()=>rE),w=await $({name:"clarity",alias:"logging",defaultConfig:zj,cwd:RJ.cwd()});if(w)Object.assign(SJ,w)}catch{}return SJ})();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"},b=q$,VN=q$.red,jH=q$.green,SN=q$.yellow,FH=q$.blue,ON=q$.magenta,XN=q$.cyan,bE=q$.white,_N=q$.gray,zH=q$.bgRed,fH=q$.bgYellow,DN=q$.bgGray,iE=q$.bold,QN=q$.dim,kN=q$.italic,xN=q$.underline,PN=q$.strikethrough,bN=q$.reset,E8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},GH={debug:"\uD83D\uDD0D",info:FH("ℹ"),success:jH("✓"),warning:fH(bE(iE(" WARN "))),error:zH(bE(iE(" ERROR ")))};iN=new PJ("stacks");T0=class T0 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}${$}`}};Gj=class Gj extends T0{code="CONFIG_NOT_FOUND";constructor($,w,A){let J=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],Y="";if(J.length===1)Y=` or alias "${J[0]}"`;else if(J.length>1)Y=` or aliases ${J.map((U)=>`"${U}"`).join(", ")}`;super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};OJ=class OJ extends T0{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}};Tj=class Tj extends T0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Hj=class Hj extends T0{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}};Q8=class Q8 extends T0{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})}};qj=class qj extends T0{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}};Kj=class Kj extends T0{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}};XJ=class XJ extends T0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};hj=class hj extends T0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}};Rj=class Rj extends T0{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 Gj($,w,A)},configLoad($,w,A){return new OJ($,w,A)},configValidation($,w,A){return new Tj($,w,A)},configMerge($,w,A,J){return new Hj($,w,A,J)},envVar($,w,A,J){return new Q8($,w,A,J)},fileSystem($,w,A){return new qj($,w,A)},typeGeneration($,w,A){return new Kj($,w,A)},schemaValidation($,w,A){return new XJ($,w,A)},browserConfig($,w,A,J){return new hj($,w,A,J)},plugin($,w,A){return new Rj($,w,A)}};NH=/^https?:\/\//;Q0=new PJ("bunfig",{showTags:!0});uN=new yj;cN=$0(QJ.cwd(),"config"),vN=$0(QJ.cwd(),"src/generated"),Vj={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:dU.join(nU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:dU.join(nU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:dU.join(nU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},Y$=Vj,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"},L={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},ew={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};yH=LH(IH);VH=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),SH=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;G0={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"};rH={platform:"darwin",async addCertificate($,w){if(await tH($,w?.verbose)){C(L.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),ew.success("Certificate is already trusted in system keychain");return}C(L.TRUST,"Adding certificate to macOS keychain",w?.verbose),await $w(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||Y$.commonName;C(L.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await $w(`sudo security delete-certificate -c "${J}" /Library/Keychains/System.keychain`),C(L.TRUST,`Removed certificate ${J} from macOS keychain`,w?.verbose)}catch(Y){throw C(L.TRUST,`Error removing certificate: ${Y}`,w?.verbose),Y}}},aH={platform:"win32",async addCertificate($,w){C(L.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await $w(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||Y$.commonName;C(L.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await $w(`certutil -delstore -enterprise Root "${J}"`),C(L.TRUST,`Removed certificate ${J} from Windows certificate store`,w?.verbose)}catch(Y){throw C(L.TRUST,`Error removing certificate: ${Y}`,w?.verbose),Y}}},sH={platform:"linux",async addCertificate($,w){C(L.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=DJ.homedir(),J=f0.LINUX_CERT_DB_FILENAME,Y=f0.LINUX_TRUST_ARGS;C(L.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let U=M8(A,J);if(U.length===0){ew.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let Z of U){C(L.TRUST,`Processing certificate database in ${Z}`,w?.verbose);try{C(L.TRUST,`Attempting to delete existing cert for ${Y$.commonName}`,w?.verbose),await $w(`certutil -d sql:${Z} -D -n ${Y$.commonName}`)}catch(B){C(L.TRUST,`Warning: Error deleting existing cert: ${B}`,w?.verbose),console.warn(`Error deleting existing cert: ${B}`)}C(L.TRUST,`Adding new certificate to ${Z}`,w?.verbose),await $w(`certutil -d sql:${Z} -A -t ${Y} -n ${Y$.commonName} -i ${$}`),ew.info(`Cert added to ${Z}`)}},async removeCertificate($,w,A){let J=A||Y$.commonName;C(L.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let Y=DJ.homedir(),U=f0.LINUX_CERT_DB_FILENAME;C(L.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let Z=M8(Y,U);if(Z.length===0){ew.warn("No certificate databases found. Cannot remove certificate.");return}for(let B of Z){C(L.TRUST,`Processing certificate database in ${B}`,w?.verbose);try{await $w(`certutil -d sql:${B} -D -n "${J}"`),ew.info(`Cert removed from ${B}`)}catch(W){C(L.TRUST,`Error removing cert from ${B}: ${W}`,w?.verbose),console.warn(`Error removing cert from ${B}: ${W}`)}}}},oH={darwin:rH,win32:aH,linux:sH}});var vj=h$(()=>{cj()});import{homedir as v8}from"node:os";import{join as m8,resolve as XM}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",eH,n8;var d8=h$(()=>{cU();eH={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:m8(v8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:m8(v8(),".stacks","ssl","stacks.localhost.crt"),keyPath:m8(v8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},n8=eH});import{execSync as $7}from"node:child_process";function mj($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function iJ($){try{let w=$7(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return mj(w)}catch{return null}}var g8=()=>{};import{existsSync as nj,statSync as dj}from"fs";import{existsSync as jZ,mkdirSync as Z7,readdirSync as W7,writeFileSync as B7}from"fs";import{homedir as J1}from"os";import{dirname as gj,resolve as b$}from"path";import Tw from"process";import{join as E7,relative as j7,resolve as lj}from"path";import wY from"process";import{existsSync as SF,mkdirSync as nM,readdirSync as dM,writeFileSync as gM}from"fs";import{homedir as l8}from"os";import{dirname as tM,resolve as P$}from"path";import c1 from"process";import{join as F7,relative as z7,resolve as pj}from"path";import AY from"process";import{existsSync as OF,mkdirSync as eM,readdirSync as $I,writeFileSync as wI}from"fs";import{dirname as JI,resolve as JY}from"path";import FZ from"process";import{Buffer as Aw}from"buffer";import{createCipheriv as f7,createDecipheriv as G7,randomBytes as p8}from"crypto";import{closeSync as t8,createReadStream as tj,createWriteStream as T7,existsSync as r8,fsyncSync as rj,openSync as aj,writeFileSync as H7}from"fs";import{access as q7,constants as sj,mkdir as K7,readdir as uJ,rename as oj,stat as Y1,unlink as cJ,writeFile as a8}from"fs/promises";import{join as U1}from"path";import y$ from"process";import{pipeline as h7}from"stream/promises";import{createGzip as ej}from"zlib";import Z1 from"process";import v0 from"process";import{Buffer as u0}from"buffer";import{createCipheriv as R7,createDecipheriv as N7,randomBytes as s8}from"crypto";import{closeSync as o8,createReadStream as $F,createWriteStream as M7,existsSync as vJ,fsyncSync as wF,openSync as AF,writeFileSync as I7}from"fs";import{access as C7,constants as JF,mkdir as L7,readdir as mJ,rename as YF,stat as W1,unlink as nJ,writeFile as e8}from"fs/promises";import{isAbsolute as y7,join as B1,resolve as V7}from"path";import X from"process";import{pipeline as S7}from"stream/promises";import{createGzip as UF}from"zlib";import E1 from"process";import m0 from"process";import dJ from"process";import{existsSync as gJ}from"fs";import{resolve as $Z}from"path";import{existsSync as O7}from"fs";import{existsSync as X7,readdirSync as _7}from"fs";import{extname as wZ,resolve as ZF}from"path";import D7 from"process";import{join as Q5,relative as k5,resolve as KF}from"path";import jY from"process";import{Buffer as c0}from"buffer";import{createCipheriv as b5,createDecipheriv as i5,randomBytes as ZZ}from"crypto";import{closeSync as WZ,createReadStream as hF,createWriteStream as u5,existsSync as pJ,fsyncSync as RF,openSync as NF,writeFileSync as c5}from"fs";import{access as v5,constants as MF,mkdir as m5,readdir as tJ,rename as IF,stat as j1,unlink as rJ,writeFile as BZ}from"fs/promises";import{isAbsolute as n5,join as F1,resolve as d5}from"path";import _ from"process";import{pipeline as g5}from"stream/promises";import{createGzip as CF}from"zlib";import z1 from"process";import n0 from"process";function J7($,w){this[$]=A7.bind(null,w)}class NZ{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 Y=this.generateKey($,A),U=J??this.options.ttl,Z=this.estimateSize(w);this.cache.set(Y,{value:w,timestamp:new Date,ttl:U,hits:0,size:Z}),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(!nj($))return!0;return dj($).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 Y=nj(A)?dj(A):null,U=Y?Y.mtime:new Date;this.set($,{value:w,fileTimestamp:U},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,Y)=>J+Y.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 MZ{metrics=[];maxMetrics=1000;async track($,w,A={}){let J=performance.now(),Y=new Date;try{let U=await w(),Z=performance.now()-J;return this.recordMetric({operation:$,duration:Z,timestamp:Y,...A}),U}catch(U){let Z=performance.now()-J;throw this.recordMetric({operation:`${$}:error`,duration:Z,timestamp:Y,...A}),U}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((Y)=>Y.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((Y)=>Y.duration),J=A.reduce((Y,U)=>Y+U,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 Q7($,w={}){let J=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return J?`${$}:${J}`:$}function k7($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function x7($){return $.getStats().size*2}function IZ($,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 Y of $)if(s(Y)&&"name"in Y){if(!J.find((Z)=>s(Z)&&("name"in Z)&&Z.name===Y.name))J.push(Y)}else if(s(Y)&&"path"in Y){if(!J.find((Z)=>s(Z)&&("path"in Z)&&Z.path===Y.path))J.push(Y)}else if(!J.some((U)=>YY(U,Y)))J.push(Y);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);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 Y=w[J];if(Y===null||Y===void 0)continue;else if(s(Y)&&s(A[J]))A[J]=IZ(A[J],Y);else if(Array.isArray(Y)&&Array.isArray(A[J]))if(Y.length>0&&A[J].length>0&&s(Y[0])&&s(A[J][0])){let U=[...Y];for(let Z of A[J])if(s(Z)&&"name"in Z){if(!U.find((W)=>s(W)&&("name"in W)&&W.name===Z.name))U.push(Z)}else if(s(Z)&&"path"in Z){if(!U.find((W)=>s(W)&&("path"in W)&&W.path===Z.path))U.push(Z)}else if(!U.some((B)=>YY(B,Z)))U.push(Z);A[J]=U}else if(Y.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...Y];for(let Z of A[J])if(!U.includes(Z))U.push(Z);A[J]=U}else A[J]=Y;else A[J]=Y}return A}function YY($,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(!YY($[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 Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!YY($[Y],w[Y]))return!1}return!0}return!1}function s($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function P7($,w){if(!OF($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return IZ(w,J)}catch{return null}}catch{return null}}async function b7({name:$="",cwd:w,defaultConfig:A}){let J=w||FZ.cwd(),Y=[".ts",".js",".mjs",".cjs",".json"],U=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let Z of U)for(let B of Y){let W=JY(J,`${Z}${B}`),E=await P7(W,A);if(E!==null)return E}try{let Z=JY(J,"package.json");if(OF(Z)){let W=(await import(Z))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return IZ(A,W)}catch{}}}catch{}return A}function i7($,w={}){let A=AY.cwd();while(A.includes("storage"))A=pj(A,"..");let J=pj(A,$||"");if(w?.relative)return z7(AY.cwd(),J);return J}async function u7(){try{let $=await b7({name:"clarity",defaultConfig:sJ,cwd:AY.cwd(),endpoint:"",headers:{}});return{...sJ,...$}}catch{return sJ}}function A$(){if(v0.env.NODE_ENV==="test"||v0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function c7(){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 XF{async format($){let w=await c7(),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:Z1.pid,hostname:w(),environment:Z1.env.NODE_ENV||"development",platform:Z1.platform,version:Z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Z1.env.NODE_ENV||Z1.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;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={...fZ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new XF,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},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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...oJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...oJ};return{...oJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:fZ.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 Y,U=0,Z=3,B=1000;while(U<Z)try{try{try{await q7(this.config.logDirectory,sj.F_OK|sj.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await K7(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Aw.from($);try{if(!r8(this.currentLogFile))await a8(this.currentLogFile,"",{mode:420});if(Y=aj(this.currentLogFile,"a",420),H7(Y,W,{flag:"a"}),rj(Y),Y!==void 0)t8(Y),Y=void 0;if((await Y1(this.currentLogFile)).size===0){if(await a8(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(E){let j=E;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<Z-1){let F=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,F);let f=B*2**U;await new Promise((z)=>setTimeout(z,f)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{t8(Y)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(W){if(U===Z-1){let j=W,F=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),W}U++;let E=B*2**(U-1);await new Promise((j)=>setTimeout(j,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 U1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return U1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return U1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Z=Math.max(1,U);if(Y.length>Z)for(let[B]of Y.slice(Z))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return p8(16).toString("hex")}generateKey(){return p8(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=p8(16),J=f7("aes-256-gcm",w,A),Y=Aw.concat([J.update($,"utf8"),J.final()]),U=J.getAuthTag();return{encrypted:Aw.concat([A,Y,U]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=ej(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(Aw.from(Aw.concat(Y)))),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 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,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await uJ(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await Y1(A).catch(()=>null))try{if(await oj(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await cJ(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await a8(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await Y1(A).catch(()=>null))await oj(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await uJ(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,B)=>B.localeCompare(Z));for(let Z of U.slice(w.maxFiles))await cJ(U1(this.config.logDirectory,Z))}}}async compressLogFile($,w){let A=tj($),J=T7(w),Y=ej();await h7(A,Y,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()})),r8(this.currentLogFile))try{let $=aj(this.currentLogFile,"r+");rj($),t8($)}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 uJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await cJ(U1(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:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=y$.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${p.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}async log($,w,...A){let J=new Date,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);if(this.fancy&&!A$()){let E=cF[$],j=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:p.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.error(F);break;case"success":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:p.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:Y,icon:E,tag:j,message:Z,level:$}),console.error(F),B){let f=B.split(`
|
|
129
|
+
`);for(let z of f)if(z.trim()&&!z.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:p.gray(` ${z}`),level:$,showTimestamp:!1}))}break}}else if(!A$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${U} ${this.environment}.${$.toUpperCase()}: ${Z}
|
|
130
|
+
`;if(B)W+=`${B}
|
|
131
|
+
`;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!A$()){let A=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:p.blue("◐"),tag:A,message:`${p.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
132
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!A$()){let j=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:p.green("✓"),tag:j,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!A$())console.error(E.trim());await this.writeToFile(E)}}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(A$())throw Error("createReadStream is not supported in browser environments");if(!r8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return tj(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=Aw.isBuffer($)?$:Aw.from($,"base64"),Y=J.slice(0,16),U=J.slice(-16),Z=J.slice(16,-16),B=G7("aes-256-gcm",A,Y);return B.setAuthTag(U),Aw.concat([B.update(Z),B.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 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),J=this.formatFileTimestamp(w);if(this.fancy&&!A$()){let U=$.split(`
|
|
133
|
+
`),Z=Math.max(...U.map((j)=>j.length))+2,B=`┌${"─".repeat(Z)}┐`,W=`└${"─".repeat(Z)}┘`,E=U.map((j)=>{let F=" ".repeat(Z-j.length-2);return`│ ${j}${F} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:p.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:p.cyan(B)})),E.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:A,message:p.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:p.cyan(W),showTimestamp:!1}))}else if(!A$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let Y=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
134
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}async prompt($){if(A$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${p.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.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(Y==="y"||Y==="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 Z=/%([sdijfo%])/g,B=0;if(A=$.replace(Z,(W,E)=>{if(E==="%")return"%";if(B>=w.length)return W;let j=w[B++];switch(E){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 W}}),B<w.length)A+=` ${w.slice(B).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!A$()){let Z=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",B=p.blue("◐");console.error(`${B} ${Z} ${p.cyan(A)}`)}let U=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
135
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}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:(Z,B)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||A$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Z)),B!==void 0)this.activeProgressBar.message=B;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(Z)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||A$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Z!==void 0)this.activeProgressBar.message=Z;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Z,B="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||A$())return;y$.stdout.write(`${"\r".padEnd(y$.stdout.columns||80)}\r`),this.log(B,Z),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))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=p.green("━".repeat(J)),Z=p.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=w||A===100?p.green("✓"):p.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${p.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=y$.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,y$.stdout.write($.lastRenderedLine),w)y$.stdout.write(`
|
|
136
|
+
`)}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 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 U=U1(this.config.logDirectory,J);if($.before)try{if((await Y1(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);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 cJ(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function aJ($,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 Y of $)if(d(Y)&&"name"in Y){if(!J.find((Z)=>d(Z)&&("name"in Z)&&Z.name===Y.name))J.push(Y)}else if(d(Y)&&"path"in Y){if(!J.find((Z)=>d(Z)&&("path"in Z)&&Z.path===Y.path))J.push(Y)}else if(!J.some((U)=>ZY(U,Y)))J.push(Y);return J}if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);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 Y=w[J];if(Y===null||Y===void 0)continue;else if(d(Y)&&d(A[J]))A[J]=aJ(A[J],Y);else if(Array.isArray(Y)&&Array.isArray(A[J]))if(Y.length>0&&A[J].length>0&&d(Y[0])&&d(A[J][0])){let U=[...Y];for(let Z of A[J])if(d(Z)&&"name"in Z){if(!U.find((W)=>d(W)&&("name"in W)&&W.name===Z.name))U.push(Z)}else if(d(Z)&&"path"in Z){if(!U.find((W)=>d(W)&&("path"in W)&&W.path===Z.path))U.push(Z)}else if(!U.some((B)=>ZY(B,Z)))U.push(Z);A[J]=U}else if(Y.every((U)=>typeof U==="string")&&A[J].every((U)=>typeof U==="string")){let U=[...Y];for(let Z of A[J])if(!U.includes(Z))U.push(Z);A[J]=U}else A[J]=Y;else A[J]=Y}return A}function CZ($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:aJ($,w);if(Array.isArray($))return A==="replace"?w:aJ($,w);if(!d(w)||!d($))return w;let J={...$};for(let Y of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,Y))continue;let U=w[Y],Z=J[Y];if(U===null||U===void 0)continue;if(Array.isArray(U)||Array.isArray(Z))if(A==="replace")J[Y]=U;else J[Y]=aJ(Z,U);else if(d(U)&&d(Z))J[Y]=CZ(Z,U,A);else J[Y]=U}return J}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(d($)&&d(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!ZY($[Y],w[Y]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function lJ($,w,A="replace"){if(!SF($))return null;try{let J=await import($),Y=J.default||J;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return CZ(w,Y,A)}catch{return null}}catch{return null}}function v7($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),Y={...w};function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=(T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase(),z=`${J}_${F.map(f).join("_")}`,H=`${J}_${F.map((T)=>T.toUpperCase()).join("_")}`;if(A)S$.info(`Checking environment variable ${z} for config ${$}.${F.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))W[E]=U(j,F);else{let T=c1.env[z]||c1.env[H];if(T!==void 0){if(A)S$.info(`Using environment variable ${T?z:H} for config ${$}.${F.join(".")}`);if(typeof j==="number")W[E]=Number(T);else if(typeof j==="boolean")W[E]=T.toLowerCase()==="true";else if(Array.isArray(j))try{let q=JSON.parse(T);if(Array.isArray(q))W[E]=q;else W[E]=T.split(",").map((K)=>K.trim())}catch{W[E]=T.split(",").map((q)=>q.trim())}else W[E]=T}}}return W}return U(Y)}async function m7({name:$="",alias:w,cwd:A,configDir:J,defaultConfig:Y,verbose:U=!1,checkEnv:Z=!0,arrayStrategy:B="replace"}){let W=Z&&typeof Y==="object"&&Y!==null&&!Array.isArray(Y)?v7($,Y,U):Y,E=A||c1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(U)S$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let F=[$,`.${$}`].filter(Boolean),f=[`${$}.config`,`.${$}.config`].filter(Boolean),z=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],T=Array.from(new Set([E,P$(E,"config"),P$(E,".config"),J?P$(E,J):void 0].filter(Boolean)));for(let q of T){if(U)S$.info(`Searching for configuration in: ${q}`);let h=[P$(E,"config"),P$(E,".config")].concat(J?[P$(E,J)]:[]).includes(q)?[...F,...f,...z,...H]:[...f,...F,...H,...z];for(let I of h)for(let N of j){let M=P$(q,`${I}${N}`),V=await lJ(M,W,B);if(V!==null){if(U)S$.success(`Configuration loaded from: ${M}`);return V}}}if($){let q=P$(l8(),".config",$),K=["config",`${$}.config`];if(w)K.push(`${w}.config`);if(U)S$.info(`Checking user config directory: ${q}`);for(let h of K)for(let I of j){let N=P$(q,`${h}${I}`),M=await lJ(N,W,B);if(M!==null){if(U)S$.success(`Configuration loaded from user config directory: ${N}`);return M}}}if($){let q=P$(l8(),".config"),K=[`.${$}.config`];if(w)K.push(`.${w}.config`);if(U)S$.info(`Checking user config directory for dotfile configs: ${q}`);for(let h of K)for(let I of j){let N=P$(q,`${h}${I}`),M=await lJ(N,W,B);if(M!==null){if(U)S$.success(`Configuration loaded from user config directory dotfile: ${N}`);return M}}}if($){let q=l8(),K=[`.${$}.config`,`.${$}`];if(w)K.push(`.${w}.config`),K.push(`.${w}`);if(U)S$.info(`Checking user home directory for dotfile configs: ${q}`);for(let h of K)for(let I of j){let N=P$(q,`${h}${I}`),M=await lJ(N,W,B);if(M!==null){if(U)S$.success(`Configuration loaded from user home directory: ${N}`);return M}}}try{let q=P$(E,"package.json");if(SF(q)){let K=await import(q),h=K[$];if(!h&&w){if(h=K[w],h&&U)S$.success(`Using alias "${w}" configuration from package.json`)}if(h&&typeof h==="object"&&!Array.isArray(h))try{if(U)S$.success(`Configuration loaded from package.json: ${h===K[$]?$:w}`);return CZ(W,h,B)}catch(I){if(U)S$.warn("Failed to merge package.json config:",I)}}}catch(q){if(U)S$.warn("Failed to load package.json:",q)}if(U)S$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function n7($,w={}){let A=wY.cwd();while(A.includes("storage"))A=lj(A,"..");let J=lj(A,$||"");if(w?.relative)return j7(wY.cwd(),J);return J}async function d7(){try{let $=await m7({name:"clarity",alias:"logging",defaultConfig:eJ,cwd:wY.cwd()});return{...eJ,...$||{}}}catch{return eJ}}function z$(){if(m0.env.NODE_ENV==="test"||m0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function g7(){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 _F{async format($){let w=await g7(),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:E1.pid,hostname:w(),environment:E1.env.NODE_ENV||"development",platform:E1.platform,version:E1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:E1.env.NODE_ENV||E1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class WY{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={...GZ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new _F,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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,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{...$Y,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$Y};return{...$Y,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:GZ.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!z$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let Y,U=0,Z=3,B=1000;while(U<Z)try{try{try{await C7(this.config.logDirectory,JF.F_OK|JF.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await L7(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:u0.from($);try{if(!vJ(this.currentLogFile))await e8(this.currentLogFile,"",{mode:420});if(Y=AF(this.currentLogFile,"a",420),I7(Y,W,{flag:"a"}),wF(Y),Y!==void 0)o8(Y),Y=void 0;if((await W1(this.currentLogFile)).size===0){if(await e8(this.currentLogFile,W,{flag:"w",mode:420}),(await W1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let j=E;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<Z-1){let F=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,F);let f=B*2**U;await new Promise((z)=>setTimeout(z,f)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{o8(Y)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(W){if(U===Z-1){let j=W,F=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),W}U++;let E=B*2**(U-1);await new Promise((j)=>setTimeout(j,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 B1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return B1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return B1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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,J=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Z=Math.max(1,U);if(Y.length>Z)for(let[B]of Y.slice(Z))this.encryptionKeys.delete(B),this.keys.delete(B)}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=R7("aes-256-gcm",w,A),Y=u0.isBuffer($)?$:u0.from($,"utf8"),U=J.update(Y),Z=J.final(),B=U.length+Z.length,W=J.getAuthTag(),E=u0.allocUnsafe(16+B+16);return A.copy(E,0),U.copy(E,16),Z.copy(E,16+U.length),W.copy(E,16+B),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=UF(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(u0.from(u0.concat(Y)))),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(z$())return;if(!this.shouldWriteToFile())return;let $=await W1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await mJ(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await W1(A).catch(()=>null))try{if(await YF(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await nJ(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await e8(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await W1(A).catch(()=>null))await YF(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await mJ(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,B)=>B.localeCompare(Z));for(let Z of U.slice(w.maxFiles))await nJ(B1(this.config.logDirectory,Z))}}}async compressLogFile($,w){let A=$F($),J=M7(w),Y=UF();await S7(A,Y,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()})),vJ(this.currentLogFile))try{let $=AF(this.currentLogFile,"r+");wF($),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(!z$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await mJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await nJ(B1(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()?k.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||z$())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:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=X.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${k.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,Y)=>{let U=k.underline(k.blue(J)),Z=this.toAbsoluteFilePath(Y);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(Z)}`,W="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${B}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),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(z$())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(y7(w)||w.startsWith("./")||w.startsWith("../"))w=V7(w);else return null;return vJ(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,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);let{consoleText:W,fileText:E}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":vF[$],f=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:k.gray(W),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:k.green(W),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.error(z),B){let H=B.split(`
|
|
137
|
+
`);for(let T of H)if(T.trim()&&!T.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:k.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!z$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}if(!this.shouldLog($))return;let j=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
138
|
+
`;if(B)j+=`${B}
|
|
139
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!z$()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!z$()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!z$()&&X.stdout.isTTY)X.stdout.write(`
|
|
140
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!z$()&&X.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)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":k.blue("◐"),tag:A,message:`${k.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
141
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":k.green("✓"),tag:j,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!z$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}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 WY(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(!vJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $F(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=u0.isBuffer($)?$:u0.from($,"base64"),Y=J.subarray(0,16),U=J.subarray(J.length-16),Z=J.subarray(16,J.length-16),B=N7("aes-256-gcm",A,Y);B.setAuthTag(U);let W=B.update(Z),E=B.final(),j=W.length+E.length,F=u0.allocUnsafe(j);return W.copy(F,0),E.copy(F,W.length),F.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 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),J=this.formatFileTimestamp(w),{consoleText:Y,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=Y.split(`
|
|
142
|
+
`),W=Math.max(...B.map((f)=>f.length))+2,E=`┌${"─".repeat(W)}┐`,j=`└${"─".repeat(W)}┘`,F=B.map((f)=>{return this.formatConsoleMessage({timestamp:A,message:k.cyan(f),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(E),showTimestamp:!1})),F.forEach((f)=>console.error(f)),console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(j),showTimestamp:!1}))}else if(!z$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${J} ${this.environment}.INFO: [BOX] ${U}
|
|
143
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(z$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${k.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.toString().trim().toLowerCase();X.stdin.removeListener("data",A);try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!1)}catch{}X.stdin.pause(),console.error(""),w(Y==="y"||Y==="yes")};try{if(typeof X.stdin.setRawMode==="function")X.stdin.setRawMode(!0)}catch{}X.stdin.resume(),X.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,E=0;if(A=$.replace(W,(j,F)=>{if(F==="%")return"%";if(E>=w.length)return j;let f=w[E++];switch(F){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return j}}),E<w.length)A+=` ${w.slice(E).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:J,fileText:Y}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${k.blue("◐")} `;console.error(`${E}${W} ${k.cyan(J)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
144
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!X.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=k.green("━".repeat(J)),Z=k.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?k.green("✓"):k.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=X.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,X.stdout.write($.lastRenderedLine),w)X.stdout.write(`
|
|
145
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||z$()||!X.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await mJ(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=B1(this.config.logDirectory,J);if($.before)try{if((await W1(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);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 nJ(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function DF($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:Y=()=>!0,fallback:U}=w,Z=Error("Unknown error occurred");for(let B=0;B<=A;B++)try{return await $()}catch(W){if(Z=W instanceof Error?W:Error(String(W)),B===A||!Y(Z))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(U!==void 0)return U;throw Z instanceof Error?Z:Error(`Unknown error: ${String(Z)}`)}function QF($){return $ instanceof a$}function l7($){return $ instanceof BY}function p7($){if(QF($))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 zY{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:J,useCamelCase:Y=!0,useBackwardCompatibility:U=!0,customParsers:Z={},verbose:B=!1,trackPerformance:W=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=J||this.generateEnvPrefix($),F={...w};return this.processObject(F,[],j,{useCamelCase:Y,useBackwardCompatibility:U,customParsers:Z,verbose:B,configName:$}),{config:F,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return n1.track("applyEnvironmentVariables",E,{configName:$});return E()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=Z.map((j)=>this.formatEnvKey(j,J.useCamelCase)),W=`${A}_${B.join("_")}`,E=J.useBackwardCompatibility?`${A}_${Z.map((j)=>j.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.processObject(U,Z,A,J);else{let j=dJ.env[W]||(E?dJ.env[E]:void 0);if(j!==void 0){if(J.verbose){let F=dJ.env[W]?W:E}try{$[Y]=this.parseEnvironmentValue(j,typeof U,W,J.customParsers,J.configName)}catch(F){if(F instanceof EY)throw F;throw Jw.envVar(W,j,typeof U,J.configName)}}}}}parseEnvironmentValue($,w,A,J,Y){for(let[U,Z]of Object.entries(J))try{return Z($)}catch{continue}for(let U of this.defaultParsers)if(U.canParse($,w))try{return U.parse($)}catch{throw Jw.envVar(A,$,`${w} (via ${U.name} parser)`,Y)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,Y]of Object.entries(dJ.env))if(J.startsWith(A)&&Y!==void 0)w[J]=Y;return w}validateEnvironmentVariable($,w,A){let J=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))J.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(Y){J.push(`Cannot parse value "${w}" as ${A}: ${Y}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:Y="text"}=A,U=J||this.generateEnvPrefix($),Z=[];switch(this.extractEnvVarInfo(w,[],U,Z),Y){case"markdown":return this.formatAsMarkdown(Z,$);case"json":return JSON.stringify(Z,null,2);default:return this.formatAsText(Z,$)}}extractEnvVarInfo($,w,A,J){for(let[Y,U]of Object.entries($)){let Z=[...w,Y],B=`${A}_${Z.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof U==="object"&&U!==null&&!Array.isArray(U))this.extractEnvVarInfo(U,Z,A,J);else J.push({key:B,type:Array.isArray(U)?"array":typeof U,description:`Configuration for ${Z.join(".")}`,example:this.generateExample(U)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
|
|
146
146
|
|
|
147
147
|
`;for(let J of $)A+=`${J.key}
|
|
148
148
|
`,A+=` Type: ${J.type}
|
|
@@ -154,97 +154,97 @@ ${J.join(`
|
|
|
154
154
|
`;A+=`| Variable | Type | Description | Example |
|
|
155
155
|
`,A+=`|----------|------|-------------|----------|
|
|
156
156
|
`;for(let J of $)A+=`| \`${J.key}\` | ${J.type} | ${J.description} | \`${J.example}\` |
|
|
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
|
-
${
|
|
157
|
+
`;return A}}function t7($,w){let A=iF("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function kF($,w,A={}){return xF($,w,A,new WeakMap)}function xF($,w,A,J){let{arrayMergeMode:Y="replace",skipNullish:U=!1,customMerger:Z}=A;if(w===null||w===void 0)return U?$:w;if(Z){let B=Z($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return PF($,w,Y,J);if(!J0(w)||!J0($))return w;return o7($,w,A,J)}function PF($,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 r7($,w);case"smart":return a7($,w,J);default:return w}return w}function r7($,w){let A=[...w];for(let J of $)if(!A.some((Y)=>zZ(Y,J)))A.push(J);return A}function a7($,w,A){if(w.length===0)return $;if($.length===0)return w;if(J0(w[0])&&J0($[0]))return s7($,w,A);if(w.every((J)=>typeof J==="string")&&$.every((J)=>typeof J==="string")){let J=[...w];for(let Y of $)if(!J.includes(Y))J.push(Y);return J}return w}function s7($,w,A){let J=[...w];for(let Y of $){if(!J0(Y)){J.push(Y);continue}let U=["id","name","key","path","type"],Z=!1;for(let B of U)if(B in Y){if(J.find((E)=>J0(E)&&(B in E)&&E[B]===Y[B])){Z=!0;break}}if(!Z)J.push(Y)}return J}function o7($,w,A,J){let Y=w;if(J0(Y)&&J.has(Y))return J.get(Y);let U={...$};if(J0(Y))J.set(Y,U);for(let Z in Y){if(!Object.prototype.hasOwnProperty.call(Y,Z))continue;let B=Y[Z],W=U[Z];if(A.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){U[Z]=B;continue}if(J0(B)&&J0(W))U[Z]=xF(W,B,A,J);else if(Array.isArray(B)||Array.isArray(W))U[Z]=PF(W,B,A.arrayMergeMode||"smart",J);else U[Z]=B}return U}function LZ($,w,A="replace"){return kF($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function zZ($,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(!zZ($[A],w[A]))return!1;return!0}if(J0($)&&J0(w)){let A=Object.keys($),J=Object.keys(w);if(A.length!==J.length)return!1;for(let Y of A){if(!Object.prototype.hasOwnProperty.call(w,Y))return!1;if(!zZ($[Y],w[Y]))return!1}return!0}return!1}function J0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class fY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:J="replace",useCache:Y=!0,cacheTtl:U,trackPerformance:Z=!0,verbose:B=!1}=A;if(Y){let E=f1.getWithFileCheck("file",$);if(E){if(B)console.log(`Configuration loaded from cache: ${$}`);return E}}let W=async()=>{if(!gJ($))return null;try{let E=`?t=${Date.now()}`,j=await import($+E),F=j.default||j,f="default"in j,z=Object.keys(j).length>0;if(!f&&!z)throw new v1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof F!=="object"||F===null||Array.isArray(F))throw new v1($,Error("Configuration must export a valid object"),"unknown");let q={config:LZ(w,F,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(Y)f1.setWithFileCheck("file",q,$,U);return q}catch(E){throw E instanceof Error?Jw.configLoad($,E):Jw.configLoad($,Error(String(E)))}};if(Z)return n1.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,A={}){for(let J of $)try{let Y=await this.loadFromPath(J,w,A);if(Y)return Y}catch(Y){if(Y instanceof Error&&Y.name==="ConfigLoadError")throw Y;if(A.verbose)console.warn(`Failed to load config from ${J}:`,Y)}return null}generateConfigPaths($,w,A){let J=this.generateNamePatterns($,A),Y=[];for(let U of J)for(let Z of this.extensions)Y.push($Z(w,`${U}${Z}`));return Y}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 DF(async()=>{return gJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!gJ($))return J;if(w||A){let Y=this.generateNamePatterns(w||"",A);for(let U of Y)for(let Z of this.extensions){let B=$Z($,`${U}${Z}`);if(await this.checkFileAccess(B))J.push(B)}}else try{let{readdirSync:Y}=await import("fs"),U=Y($);for(let Z of U)if(this.looksLikeConfigFile(Z)){let B=$Z($,Z);if(await this.checkFileAccess(B))J.push(B)}}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(!gJ($))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:Y}=await import("fs"),U=Y($,"utf8");JSON.parse(U)}catch(Y){w.push(`Invalid JSON syntax: ${Y}`)}}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 Y=await this.loadFromPath(J,{},w);if(Y)A.set(J,Y.config)}catch(Y){if(w.verbose)console.warn(`Failed to preload ${J}:`,Y)}})),A}}class yZ{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:Y=!0,validateTypes:U=!0,customRules:Z=[],trackPerformance:B=!0,verbose:W=!1}=A,E=async()=>{let j=[],F=[],f={stopOnFirstError:J,validateRequired:Y,validateTypes:U,customRules:Z,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,f);else if(Array.isArray(w))return this.validateWithRules($,[...w,...Z],f);else return this.validateWithJSONSchema($,w,f)}catch(z){return j.push({path:"",message:`Validation failed: ${z}`,rule:"system"}),{isValid:!1,errors:j,warnings:F}}};if(B)return await n1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!O7(w))throw new m1(w,[{path:"",message:"Schema file does not exist"}]);let J=await import(w),Y=J.default||J;if(Array.isArray(Y))return this.validateWithRules($,Y,A);else return this.validateWithJSONSchema($,Y,A)}catch(J){throw new m1(w,[{path:"",message:`Failed to load schema: ${J}`}])}}validateWithJSONSchema($,w,A){let J=[],Y=[];return this.validateObjectAgainstSchema($,w,"",J,Y,A),{isValid:J.length===0,errors:J,warnings:Y}}validateObjectAgainstSchema($,w,A,J,Y,U){if(U.validateTypes&&w.type){let Z=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(Z)){if(J.push({path:A,message:`Expected type ${B.join(" or ")}, got ${Z}`,expected:B.join(" or "),actual:Z,rule:"type"}),U.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"}),U.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 Z=0;Z<$.length;Z++){let B=A?`${A}[${Z}]`:`[${Z}]`;if(this.validateObjectAgainstSchema($[Z],w.items,B,J,Y,U),U.stopOnFirstError&&J.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let Z=$;if(U.validateRequired&&w.required){for(let B of w.required)if(!(B in Z)){if(J.push({path:A?`${A}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),U.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in Z){let E=A?`${A}.${B}`:B;if(this.validateObjectAgainstSchema(Z[B],W,E,J,Y,U),U.stopOnFirstError&&J.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(Z))if(!B.has(W))Y.push({path:A?`${A}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let J=[],Y=[];for(let U of w)try{let Z=this.getValueByPath($,U.path),B=this.validateWithRule(Z,U,U.path);if(J.push(...B),A.stopOnFirstError&&J.length>0)break}catch(Z){J.push({path:U.path,message:`Rule validation failed: ${Z}`,rule:"system"})}return{isValid:J.length===0,errors:J,warnings:Y}}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 Y=Array.isArray($)?"array":typeof $;if(Y!==w.type)J.push({path:A,message:w.message||`Expected type ${w.type}, got ${Y}`,expected:w.type,actual:Y,rule:"type"})}if(w.min!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y<w.min)J.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:Y,rule:"min"})}if(w.max!==void 0){let Y=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(Y>w.max)J.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:Y,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 Y=w.validator($);if(Y)J.push({path:A,message:w.message||Y,rule:"custom"})}return J}getValueByPath($,w){if(!w)return $;let A=w.split("."),J=$;for(let Y of A)if(J&&typeof J==="object"&&Y in J)J=J[Y];else return;return J}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let J of A){let[,Y,U,Z]=J;w.push({path:Y,required:!U,type:this.mapTypeScriptType(Z)})}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:nF},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class VZ{fileLoader=new fY;envProcessor=new zY;validator=new yZ;async loadConfig($){let w=Date.now(),{cache:A,performance:J,schema:Y,validate:U,...Z}=$;try{if(A?.enabled){let W=this.checkCache(Z.name||"",Z);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(Z,!0,A)}catch(W){let E=Z.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(E)throw W;B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`No configuration file found for "${Z.name||"config"}", using defaults with environment variables`]}}else if(W instanceof Error&&W.name==="ConfigLoadError"){let j=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),F=!j&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),f=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(E&&(f||j))throw W;if(F&&(!E||!f))B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!E)B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else B={...await this.applyEnvironmentVariables(Z.name||"",Z.defaultConfig,Z.checkEnv!==!1,Z.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(Y||U)await this.validateConfiguration(B.config,Y,U,Z.name);if(A?.enabled&&B)this.cacheResult(Z.name||"",B,A,Z);if(J?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:Z.name,timestamp:new Date};if(J.onMetrics)J.onMetrics(W);if(J.slowThreshold&&W.duration>J.slowThreshold)H0.warn(`Slow configuration loading detected: ${W.duration}ms for ${Z.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw H0.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,A){let{name:J="",alias:Y,cwd:U,configDir:Z,defaultConfig:B,checkEnv:W=!0,arrayStrategy:E="replace",verbose:j=!1}=$,F=U||Tw.cwd(),f=[],z=await this.loadLocalConfiguration(J,Y,F,Z,B,E,j,W,A);if(z)return f.push(...this.getLocalSearchPaths(J,Y,F,Z)),this.finalizeResult(z,f,W,J,j);let H=await this.loadHomeConfiguration(J,Y,B,E,j,W);if(H)return f.push(...this.getHomeSearchPaths(J,Y)),this.finalizeResult(H,f,W,J,j);let T=await this.loadPackageJsonConfiguration(J,Y,F,B,E,j,W);if(T)return f.push(b$(F,"package.json")),this.finalizeResult(T,f,W,J,j);if(f.push(...this.getAllSearchPaths(J,Y,F,Z)),w)throw Jw.configNotFound(J,f,Y);return{...await this.applyEnvironmentVariables(J,B,W,j),warnings:[`No configuration file found for "${J}"${Y?` or alias "${Y}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,Y,U,Z,B,W){let E=B?u1($,Y,Z):Y,j=this.getLocalDirectories(A,J);for(let F of j){if(Z)H0.info(`Searching for configuration in: ${F}`);let f=this.fileLoader.generateConfigPaths($,F,w),z=await this.fileLoader.tryLoadFromPaths(f,E,{arrayStrategy:U,verbose:Z,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(z){if(Z)H0.success(`Configuration loaded from: ${z.source.path}`);return z}}return null}async loadHomeConfiguration($,w,A,J,Y,U){if(!$)return null;let Z=U?u1($,A,Y):A,B=[b$(J1(),".config",$),b$(J1(),".config"),J1()];for(let W of B){if(Y)H0.info(`Checking home directory: ${W}`);let E=this.fileLoader.generateConfigPaths($,W,w),j=await this.fileLoader.tryLoadFromPaths(E,Z,{arrayStrategy:J,verbose:Y});if(j){if(Y)H0.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,J,Y,U,Z){let B=Z?u1($,J,U):J;try{let W=b$(A,"package.json");if(!jZ(W))return null;let E=await import(W),j=E[$],F=$;if(!j&&w)j=E[w],F=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(U)H0.success(`Configuration loaded from package.json: ${F}`);return{config:LZ(B,j,Y),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(U)H0.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}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:u1($,w,J),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,J,Y){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,J){let Y=[];if(A){let U=A($);if(U)Y.push(...U)}if(w){let U=await this.validator.validateConfiguration($,w);if(!U.isValid)Y.push(...U.errors.map((Z)=>Z.path?`${Z.path}: ${Z.message}`:Z.message))}if(Y.length>0)throw Jw.configValidation(J||"unknown",Y,J)}checkCache($,w){let A=this.generateCacheKey($,w);return f1.get(A)||null}cacheResult($,w,A,J){let Y=this.generateCacheKey($,J);f1.set(Y,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 Y=[];return Y.push(...this.getLocalSearchPaths($,w,A,J)),Y.push(...this.getHomeSearchPaths($,w)),Y.push(b$(A,"package.json")),Y}getLocalSearchPaths($,w,A,J){let Y=this.getLocalDirectories(A,J),U=[];for(let Z of Y)U.push(...this.fileLoader.generateConfigPaths($,Z,w));return U}getHomeSearchPaths($,w){if(!$)return[];let A=[b$(J1(),".config",$),b$(J1(),".config"),J1()],J=[];for(let Y of A)J.push(...this.fileLoader.generateConfigPaths($,Y,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function WF($){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 e7($){return d0.loadConfig({...$,__strictErrorHandling:!0})}async function bF($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await d0.loadConfig($);else J=await d0.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return J?.config??w}catch(J){let Y=J instanceof Error?J.name:"UnknownError",U=J instanceof Error?J.message:String(J);if(!(Y==="ConfigNotFoundError"||Y==="ConfigLoadError"||Y==="ConfigValidationError"||U.includes("config"))&&$.verbose)H0.warn("Unexpected error loading config, using defaults:",[J instanceof Error?J:Error(String(J))]);let B=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await d0.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function $5($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await d0.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"&&WF(A)))return(await d0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await d0.loadConfig({...$,cwd:$.cwd||Tw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&WF(w)))return(await d0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function w5($,w,A="replace"){let J=new fY;try{let Y=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return Y?Y.config:null}catch{return null}}function u1($,w,A=!1){let J=new zY,Y=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function U(Z,B=[]){let W={...Z};for(let[E,j]of Object.entries(Z)){let F=[...B,E],f=[`${Y}_${F.join("_").toUpperCase()}`,`${Y}_${F.map((T)=>T.toUpperCase()).join("")}`,`${Y}_${F.map((T)=>T.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],z,H;for(let T of f)if(z=Tw.env[T],z!==void 0){H=T;break}if(z!==void 0&&H)if(typeof j==="boolean")W[E]=["true","1","yes"].includes(z.toLowerCase());else if(typeof j==="number"){let T=Number(z);if(!Number.isNaN(T))W[E]=T}else if(Array.isArray(j))try{W[E]=JSON.parse(z)}catch{W[E]=z.split(",").map((T)=>T.trim())}else W[E]=z;else if(j&&typeof j==="object"&&!Array.isArray(j))W[E]=U(j,F)}return W}return U(w)}function A5($){let w=b$(Tw.cwd(),$.configDir),A=b$(Tw.cwd(),$.generatedDir),J=b$(A,"config-types.ts");if(!jZ(gj(J)))Z7(gj(J),{recursive:!0,mode:511});let Y=jZ(w)?W7(w).map((Z)=>Z.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],U=`// Generated by bunfig v${_5}
|
|
158
|
+
export type ConfigNames = ${Y.length?`'${Y.join("' | '")}'`:"string"}
|
|
159
|
+
`;B7(J,U,{mode:438})}function J5($){let w=null,A=null,J=()=>{if(!A)A=bF($).then((U)=>{return w=U,U},(U)=>{let Z="defaultConfig"in $?$.defaultConfig:{};if(w=Z,"verbose"in $&&$.verbose)H0.warn("Config loading failed, using defaults:",[U instanceof Error?U:Error(String(U))]);return Z});return A},Y="defaultConfig"in $?$.defaultConfig:{};return w=Y,J(),new Proxy({},{get(U,Z){if(w)return w[Z];let B=Y[Z];return J(),B},has(U,Z){return Z in(w||Y)},ownKeys(){return Object.keys(w||Y)},getOwnPropertyDescriptor(U,Z){return Object.getOwnPropertyDescriptor(w||Y,Z)},set(U,Z,B){if(!w)w={...Y};return w[Z]=B,!0}})}function Y5($){let w=ZF(D7.cwd(),$?.configDir||"./config");function A(){if(!X7(w))return[];let Y=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),U=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],Z=_7(w).filter((W)=>Y.has(wZ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:E}of Z){let j=wZ(E).toLowerCase(),F=B.get(W);if(!F){B.set(W,E);continue}let f=wZ(F).toLowerCase();if(U.indexOf(j)<U.indexOf(f))B.set(W,E)}return Array.from(B.entries()).map(([W,E])=>({base:W,file:E})).sort((W,E)=>W.base.localeCompare(E.base))}function J(){let Y=A(),U=Y.map((E)=>E.base),Z=U.length?U.map((E)=>`'${E}'`).join(" | "):"string",B=Y.length?`{
|
|
160
|
+
${Y.map((E)=>{let j=ZF(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${j}').default`}).join(`,
|
|
161
161
|
`)}
|
|
162
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
163
|
-
export type ConfigByName = ${
|
|
162
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${Z}
|
|
163
|
+
export type ConfigByName = ${B}
|
|
164
164
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
165
165
|
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 T of
|
|
168
|
-
`;if(
|
|
169
|
-
`;if(
|
|
170
|
-
`);if(this[
|
|
171
|
-
`,
|
|
172
|
-
`),
|
|
173
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
174
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
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 Y
|
|
177
|
-
`))if(
|
|
166
|
+
`}return{name:"bunfig-plugin",setup(Y){Y.onResolve({filter:/^virtual:bunfig-types$/},(U)=>{return{path:U.path,namespace:"bunfig-virtual"}}),Y.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function x5($,w={}){let A=jY.cwd();while(A.includes("storage"))A=KF(A,"..");let J=KF(A,$||"");if(w?.relative)return k5(jY.cwd(),J);return J}function G$(){if(n0.env.NODE_ENV==="test"||n0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function l5(){if(n0.env.NODE_ENV==="test"||n0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n0<"u"){let $=n0.type;if($==="renderer"||$==="worker")return!1;return!!(n0.versions&&(n0.versions.node||n0.versions.bun))}return!1}class pF{async format($){let w=await l5(),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:z1.pid,hostname:w(),environment:z1.env.NODE_ENV||"development",platform:z1.platform,version:z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:z1.env.NODE_ENV||z1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Hw{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={...FY},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 Y=this.generateKeyId(),U=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,U),this.encryptionKeys.set(Y,{key:U,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{...EZ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...EZ};return{...EZ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:FY.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!G$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let Y,U=0,Z=3,B=1000;while(U<Z)try{try{try{await v5(this.config.logDirectory,MF.F_OK|MF.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await m5(this.config.logDirectory,{recursive:!0,mode:493});else if(E.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw E;else throw E}}catch(E){throw console.error("Debug: [writeToFile] Failed to create log directory:",E),E}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:c0.from($);try{if(!pJ(this.currentLogFile))await BZ(this.currentLogFile,"",{mode:420});if(Y=NF(this.currentLogFile,"a",420),c5(Y,W,{flag:"a"}),RF(Y),Y!==void 0)WZ(Y),Y=void 0;if((await j1(this.currentLogFile)).size===0){if(await BZ(this.currentLogFile,W,{flag:"w",mode:420}),(await j1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let j=E;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(U<Z-1){let F=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Z}:`,F);let f=B*2**U;await new Promise((z)=>setTimeout(z,f)),U++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(Y!==void 0)try{WZ(Y)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(W){if(U===Z-1){let j=W,F=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",F),W}U++;let E=B*2**(U-1);await new Promise((j)=>setTimeout(j,E))}})();this.pendingOperations.push(A);let J=this.pendingOperations.length-1;try{await A}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}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 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(G$())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((Y)=>{console.error("Error rotating keys:",Y)})},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 Y=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),U=typeof w.maxKeys==="number"?w.maxKeys:1,Z=Math.max(1,U);if(Y.length>Z)for(let[B]of Y.slice(Z))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return ZZ(16).toString("hex")}generateKey(){return ZZ(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=ZZ(16),J=b5("aes-256-gcm",w,A),Y=c0.isBuffer($)?$:c0.from($,"utf8"),U=J.update(Y),Z=J.final(),B=U.length+Z.length,W=J.getAuthTag(),E=c0.allocUnsafe(16+B+16);return A.copy(E,0),U.copy(E,16),Z.copy(E,16+U.length),W.copy(E,16+B),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=CF(),Y=[];J.on("data",(U)=>Y.push(U)),J.on("end",()=>w(c0.from(c0.concat(Y)))),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(G$())return;if(!this.shouldWriteToFile())return;let $=await j1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let Y=await tJ(this.config.logDirectory),U=Y.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,E)=>{let j=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),Z=U.length>0?Number.parseInt(U[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${A}.${Z}`;if(await j1(A).catch(()=>null))try{if(await IF(A,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await rJ(B)}catch(W){console.error("Error compressing rotated file:",W)}if(U.length===0&&!Y.some((W)=>W.endsWith(".log.1")))try{let W=`${A}.1`;await BZ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let Y=new Date().toISOString().replace(/[:.]/g,"-"),U=A.replace(/\.log$/,`-${Y}.log`);if(await j1(A).catch(()=>null))await IF(A,U)}if(this.currentLogFile=J,w.maxFiles){let U=(await tJ(this.config.logDirectory)).filter((Z)=>Z.startsWith(this.name)).sort((Z,B)=>B.localeCompare(Z));for(let Z of U.slice(w.maxFiles))await rJ(F1(this.config.logDirectory,Z))}}}async compressLogFile($,w){let A=hF($),J=u5(w),Y=CF();await g5(A,Y,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()})),pJ(this.currentLogFile))try{let $=NF(this.currentLogFile,"r+");RF($),WZ($)}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(!G$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await tJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await rJ(F1(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||G$())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:Y,level:U,showTimestamp:Z=!0}=$,B=(z)=>z.replace(this.ANSI_PATTERN,"");if(!this.fancy){let z=[];if(Z)z.push(w);if(U==="warning")z.push("WARN");else if(U==="error")z.push("ERROR");else if(A)z.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)z.push(J.replace(/[[\]]/g,""));return z.push(Y),z.join(" ")}let W=_.stdout.columns||120,E="";if(U==="warning"||U==="error")E=`${A} ${Y}`;else if(U==="info"||U==="success")E=`${A} ${J} ${Y}`;else E=`${A} ${J} ${i.cyan(Y)}`;if(!Z)return E.trim();let j=B(E).trim().length,F=B(w).length,f=Math.max(1,W-2-j-F);return`${E.trim()}${" ".repeat(f)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(U,Z)=>{let B=Number.parseInt(Z,10);return B<w[0].length?String(w[0][B]):U});let A=/%([sdijfo%])/g,J=0,Y=$.replace(A,(U,Z)=>{if(Z==="%")return"%";if(J>=w.length)return U;let B=w[J++];switch(Z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return U}});if(J<w.length)Y+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`;return Y}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,J,Y)=>{let U=i.underline(i.blue(J)),Z=this.toAbsoluteFilePath(Y);if(Z&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(Z)}`,W="\x1B]8;;",E="\x1B\\";return`\x1B]8;;${B}\x1B\\${U}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${Y}\x1B\\${U}\x1B]8;;\x1B\\`;return U}),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(G$())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(n5(w)||w.startsWith("./")||w.startsWith("../"))w=d5(w);else return null;return pJ(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,Y=this.formatConsoleTimestamp(J),U=this.formatFileTimestamp(J),Z,B;if(w instanceof Error)Z=w.message,B=w.stack;else Z=this.formatMessage(w,A);let{consoleText:W,fileText:E}=this.buildOutputTexts(Z);if(this.shouldStyleConsole()){let F=this.options.showIcons===!1?"":s5[$],f=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:i.gray(W),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"success":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:i.green(W),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:Y,icon:F,tag:f,message:W,level:$}),console.error(z),B){let H=B.split(`
|
|
167
|
+
`);for(let T of H)if(T.trim()&&!T.includes(Z))console.error(this.formatConsoleMessage({timestamp:Y,message:i.gray(` ${T}`),level:$,showTimestamp:!1}))}break}}else if(!G$()){if(console.error(`${U} ${this.environment}.${$.toUpperCase()}: ${Z}`),B)console.error(B)}let j=`${U} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
168
|
+
`;if(B)j+=`${B}
|
|
169
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return A;let J=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:J,lastRenderedLine:""},this.shouldStyleConsole()&&!G$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!G$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!G$()&&_.stdout.isTTY)_.stdout.write(`
|
|
170
|
+
`);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!G$()&&_.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)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:A,message:`${i.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),Y=Math.round(J-w),U=`${$} completed in ${Y}ms`,Z=new Date,B=this.formatConsoleTimestamp(Z),E=`${this.formatFileTimestamp(Z)} ${this.environment}.INFO: ${U}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
171
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":i.green("✓"),tag:j,message:`${U}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!G$())console.error(E.trim());if(this.shouldWriteToFile())await this.writeToFile(E)}}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 Hw(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(G$())throw Error("createReadStream is not supported in browser environments");if(!pJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return hF(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=c0.isBuffer($)?$:c0.from($,"base64"),Y=J.subarray(0,16),U=J.subarray(J.length-16),Z=J.subarray(16,J.length-16),B=i5("aes-256-gcm",A,Y);B.setAuthTag(U);let W=B.update(Z),E=B.final(),j=W.length+E.length,F=c0.allocUnsafe(j);return W.copy(F,0),E.copy(F,W.length),F.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 G$()}isServerMode(){return!G$()}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),{consoleText:Y,fileText:U}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=Y.split(`
|
|
172
|
+
`),W=Math.max(...B.map((f)=>f.length))+2,E=`┌${"─".repeat(W)}┐`,j=`└${"─".repeat(W)}┘`,F=B.map((f)=>{return this.formatConsoleMessage({timestamp:A,message:i.cyan(f),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:i.cyan(E),showTimestamp:!1})),F.forEach((f)=>console.error(f)),console.error(this.formatConsoleMessage({timestamp:A,message:i.cyan(j),showTimestamp:!1}))}else if(!G$())console.error(`${J} ${this.environment}.INFO: [BOX] ${U}`);let Z=`${J} ${this.environment}.INFO: [BOX] ${U}
|
|
173
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Z)}async prompt($){if(G$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let A=(J)=>{let Y=J.toString().trim().toLowerCase();_.stdin.removeListener("data",A);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),w(Y==="y"||Y==="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 W=/%([sdijfo%])/g,E=0;if(A=$.replace(W,(j,F)=>{if(F==="%")return"%";if(E>=w.length)return j;let f=w[E++];switch(F){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return j}}),E<w.length)A+=` ${w.slice(E).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:J,fileText:Y}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${E}${W} ${i.cyan(J)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
174
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),Y=$.barLength-J,U=i.green("━".repeat(J)),Z=i.gray("━".repeat(Y)),B=`[${U}${Z}]`,W=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?i.green("✓"):i.blue("▶"),F=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",f=`\r${j}${F} ${B} ${W}${E}`,z=_.stdout.columns||80,H=" ".repeat(Math.max(0,z-f.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${f}${H}`,_.stdout.write($.lastRenderedLine),w)_.stdout.write(`
|
|
175
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||G$()||!_.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(G$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await tJ(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=F1(this.config.logDirectory,J);if($.before)try{if((await j1(U)).mtime>=$.before)continue}catch(Z){console.error(`Failed to get stats for file ${U}:`,Z);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 rJ(J),console.warn(`Deleted log file: ${J}`)}catch(Y){console.error(`Failed to delete log file ${J}:`,Y)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var w7,A7=($)=>$,Y7=($,w)=>{for(var A in w)w7($,A,{get:w[A],enumerable:!0,configurable:!0,set:J7.bind(w,A)})},U7=($,w)=>()=>($&&(w=$($=0)),w),VF,iF,f1,n1,uF,U5,Z5,BF,sJ,fZ,V$,p,W5,EF,B5,jF,E5,j5,AZ,F5,FF,zF,JZ,z5,f5,G5,T5,oJ,cF,H5,S$,q5,K5,fF,eJ,GZ,f$,k,h5,GF,R5,TF,N5,M5,YZ,I5,HF,qF,C5,UZ,L5,y5,V5,S5,O5,$Y,vF,X5,_5="0.15.6",a$,BY,v1,TZ,HZ,EY,qZ,KZ,m1,hZ,RZ,Jw,mF,nF,H0,d0,dF,gF,D5,P5,lF,FY,kI,K$,i,gI,p5,lI,t5,pI,tI,LF,rI,r5,a5,aI,yF,sI,oI,eI,$4,w4,EZ,s5,A4;var SZ=h$(()=>{w7=Object.defineProperty;VF={};Y7(VF,{withErrorRecovery:()=>DF,tryLoadConfig:()=>w5,loadConfigWithResult:()=>e7,loadConfig:()=>bF,isRetryableError:()=>p7,isConfigNotFoundError:()=>l7,isBunfigError:()=>QF,globalPerformanceMonitor:()=>n1,globalCache:()=>f1,getEnvOrDefault:()=>t7,generateConfigTypes:()=>A5,defaultGeneratedDir:()=>gF,defaultConfigDir:()=>dF,deepMergeWithArrayStrategy:()=>LZ,deepMerge:()=>kF,createLibraryConfig:()=>J5,config:()=>$5,bunfigPlugin:()=>Y5,applyEnvVarsToConfig:()=>u1,TypeGenerationError:()=>KZ,SchemaValidationError:()=>m1,PluginError:()=>RZ,PerformanceMonitor:()=>MZ,FileSystemError:()=>qZ,ErrorFactory:()=>Jw,EnvVarError:()=>EY,EnvProcessor:()=>zY,ConfigValidator:()=>yZ,ConfigValidationError:()=>TZ,ConfigNotFoundError:()=>BY,ConfigMergeError:()=>HZ,ConfigLoader:()=>VZ,ConfigLoadError:()=>v1,ConfigFileLoader:()=>fY,ConfigCache:()=>NZ,CacheUtils:()=>uF,BunfigError:()=>a$,BrowserConfigError:()=>hZ,ArrayMergeStrategies:()=>mF});D5=U7(async()=>{iF=import.meta.require,f1=new NZ,n1=new MZ,uF={createKey:Q7,isEquivalent:k7,estimateMemoryUsage:x7},U5=JY(FZ.cwd(),"config"),Z5=JY(FZ.cwd(),"src/generated"),BF=AY.env.CLARITY_LOG_DIR||F7(i7(),"logs"),sJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BF,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},fZ=await u7(),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"},p=V$,W5=V$.red,EF=V$.green,B5=V$.yellow,jF=V$.blue,E5=V$.magenta,j5=V$.cyan,AZ=V$.white,F5=V$.gray,FF=V$.bgRed,zF=V$.bgYellow,JZ=V$.bold,z5=V$.dim,f5=V$.italic,G5=V$.underline,T5=V$.reset,oJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cF={debug:"\uD83D\uDD0D",info:jF("ℹ"),success:EF("✓"),warning:zF(AZ(JZ(" WARN "))),error:FF(AZ(JZ(" ERROR ")))},H5=new UY("stacks"),S$=new UY("bunfig",{showTags:!0}),q5=P$(c1.cwd(),"config"),K5=P$(c1.cwd(),"src/generated"),fF=wY.env.CLARITY_LOG_DIR||E7(n7(),"logs"),eJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fF,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},GZ=await d7(),f$={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=f$,h5=f$.red,GF=f$.green,R5=f$.yellow,TF=f$.blue,N5=f$.magenta,M5=f$.cyan,YZ=f$.white,I5=f$.gray,HF=f$.bgRed,qF=f$.bgYellow,C5=f$.bgGray,UZ=f$.bold,L5=f$.dim,y5=f$.italic,V5=f$.underline,S5=f$.strikethrough,O5=f$.reset,$Y={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},vF={debug:"\uD83D\uDD0D",info:TF("ℹ"),success:GF("✓"),warning:qF(YZ(UZ(" WARN "))),error:HF(YZ(UZ(" ERROR ")))},X5=new WY("stacks"),a$=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}`}},BY=class extends a${code="CONFIG_NOT_FOUND";constructor(w,A,J){let Y=J?` or alias "${J}"`:"";super(`Configuration "${w}"${Y} not found`,{configName:w,alias:J,searchPaths:A,searchPathCount:A.length})}},v1=class extends a${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}},TZ=class extends a${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},HZ=class extends a${code="CONFIG_MERGE_ERROR";constructor(w,A,J,Y){super(`Failed to merge configuration from "${w}" with "${A}": ${J.message}`,{sourcePath:w,targetPath:A,configName:Y,originalError:J.name,originalMessage:J.message});this.cause=J}},EY=class extends a${code="ENV_VAR_ERROR";constructor(w,A,J,Y){super(`Failed to parse environment variable "${w}" with value "${A}" as ${J}`,{envKey:w,envValue:A,expectedType:J,configName:Y})}},qZ=class extends a${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}},KZ=class extends a${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}},m1=class extends a${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})}},hZ=class extends a${code="BROWSER_CONFIG_ERROR";constructor(w,A,J,Y){super(`Failed to fetch configuration from "${w}": ${A} ${J}`,{endpoint:w,status:A,statusText:J,configName:Y})}},RZ=class extends a${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}},Jw={configNotFound($,w,A){return new BY($,w,A)},configLoad($,w,A){return new v1($,w,A)},configValidation($,w,A){return new TZ($,w,A)},configMerge($,w,A,J){return new HZ($,w,A,J)},envVar($,w,A,J){return new EY($,w,A,J)},fileSystem($,w,A){return new qZ($,w,A)},typeGeneration($,w,A){return new KZ($,w,A)},schemaValidation($,w,A){return new m1($,w,A)},browserConfig($,w,A,J){return new hZ($,w,A,J)},plugin($,w,A){return new RZ($,w,A)}},mF={replace:"replace",concat:"concat",smart:"smart"},nF=/^https?:\/\//,H0=new WY("bunfig",{showTags:!0}),d0=new VZ,dF=b$(Tw.cwd(),"config"),gF=b$(Tw.cwd(),"src/generated")});P5=jY.env.CLARITY_LOG_DIR||Q5(x5(),"logs"),lF={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:P5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},FY={...lF},kI=(async()=>{try{let{loadConfig:$}=await D5().then(()=>VF),w=await $({name:"clarity",alias:"logging",defaultConfig:lF,cwd:jY.cwd()});if(w)Object.assign(FY,w)}catch{}return FY})();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`,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=K$,gI=K$.red,p5=K$.green,lI=K$.yellow,t5=K$.blue,pI=K$.magenta,tI=K$.cyan,LF=K$.white,rI=K$.gray,r5=K$.bgRed,a5=K$.bgYellow,aI=K$.bgGray,yF=K$.bold,sI=K$.dim,oI=K$.italic,eI=K$.underline,$4=K$.strikethrough,w4=K$.reset,EZ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},s5={debug:"\uD83D\uDD0D",info:t5("ℹ"),success:p5("✓"),warning:a5(LF(yF(" WARN "))),error:r5(LF(yF(" ERROR ")))};A4=new Hw("stacks")});var G1={};TW(G1,{safeStringify:()=>Y0,safeDeleteFile:()=>_Z,resolvePathRewrite:()=>XZ,redactSensitive:()=>GY,isValidRootCA:()=>OZ,isSingleProxyOptions:()=>g1,isSingleProxyConfig:()=>J6,isMultiProxyOptions:()=>Kw,isMultiProxyConfig:()=>sF,getSudoPassword:()=>qw,getPrimaryDomain:()=>TY,extractHostname:()=>A6,execSudoSync:()=>d1,debugLog:()=>G});import{execSync as tF}from"node:child_process";import*as aF from"node:fs/promises";function qw(){return process.env.SUDO_PASSWORD}function d1($){let w=qw(),A=$.replace(/'/g,"'\\''");if(w)return tF(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return tF(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function G($,w,A){if(A)o5.debug(`[rpx:${$}] ${w}`)}function w6($){let w=$.toLowerCase();return e5.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function GY($){if(Array.isArray($))return $.map((A)=>GY(A));if(typeof $==="string")return $6.test($)?rF:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(w6(A)){w[A]=rF;continue}w[A]=GY(J)}return w}function Y0($,w){return JSON.stringify(GY($),null,w)}function A6($){if(Kw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(g1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function OZ($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function TY($){if(!$)return"stacks.localhost";if(Kw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(g1($))return $.to||"stacks.localhost";return"stacks.localhost"}function sF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Kw($){return"proxies"in $&&Array.isArray($.proxies)}function g1($){return"to"in $&&typeof $.to==="string"}function J6($){return!!($&&("to"in $)&&!("proxies"in $))}function XZ($,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,Y=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:J,targetPath:Y}}return null}async function _Z($,w){try{await aF.unlink($),G("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")G("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var o5,rF="[redacted]",e5,$6;var U$=h$(()=>{SZ();o5=new Hw("rpx",{showTags:!1});e5=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),$6=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as HY}from"node:child_process";import{homedir as Y6}from"node:os";import{join as U6}from"node:path";function qY(){return U6(Y6(),"Library/Keychains/login.keychain-db")}function QZ(){return[H1,qY()]}function oF($,w=DZ){let A=HY(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),J=[];for(let Y of A.split(`
|
|
176
|
+
`)){let U=Y.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(U)J.push(U[1].toUpperCase())}return J}function kZ($){if(process.platform!=="darwin")return;let w=iJ($.caPath);if(!w)return;let A=$.commonName??DZ,J=$.keychains??QZ();for(let Y of J)for(let U of oF(Y,A)){if(U===w)continue;try{if(Y.startsWith("/Library"))d1(`security delete-certificate -Z ${U} "${Y}"`);else HY(`security delete-certificate -Z ${U} "${Y}"`,{stdio:"ignore"});G("ssl",`Removed stale Root CA ${U} from ${Y}`,$.verbose)}catch{}}}function xZ($,w,A){if(process.platform!=="darwin")return KY($,A);try{let Y=HY(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return G("ssl",`verify-cert ${w}: ${Y?"trusted":"not trusted"}`,A?.verbose),Y}catch{return!1}}function KY($,w){let A=iJ($);if(!A)return!1;for(let J of QZ())try{let Y=HY(`security find-certificate -a -Z "${J}" 2>/dev/null || true`,{encoding:"utf8"});for(let U of Y.split(`
|
|
177
|
+
`))if(U.toUpperCase().includes("SHA-256")){if(U.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return G("ssl",`Root CA fingerprint found in ${J}`,w?.verbose),!0}}catch{}return!1}var T1="-d -r trustRoot -p ssl -p basic",H1="/Library/Keychains/System.keychain",DZ="rpx.localhost";var PZ=h$(()=>{g8();U$()});import{execSync as q1}from"node:child_process";import T$ from"node:fs/promises";import*as bZ from"node:os";import{homedir as hY}from"node:os";import{join as O$}from"node:path";import*as Yw from"node:process";function w9($){return{caCertPath:O$($,W6),caKeyPath:O$($,B6)}}async function E6($,w){try{let[A,J]=await Promise.all([T$.readFile($.caCertPath,"utf8"),T$.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!J.includes("PRIVATE KEY-----"))return G("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:J}}catch(A){return G("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function eF($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function A9($){let A=TY($).replace(/\*/g,"wildcard"),J=O$(hY(),".stacks","ssl"),Y=J;if(typeof $?.https==="object")return Y=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:J,{caCertPath:$.https.caCertPath||O$(Y,`${A}.ca.crt`),certPath:$.https.certPath||O$(Y,`${A}.crt`),keyPath:$.https.keyPath||O$(Y,`${A}.key`)};return{caCertPath:O$(Y,`${A}.ca.crt`),certPath:O$(Y,`${A}.crt`),keyPath:O$(Y,`${A}.key`)}}function $9($){let w=new Set;if(Kw($))$.proxies.forEach((A)=>{let J=A.to||"rpx.localhost";eF(J).forEach((Y)=>w.add(Y))});else if(g1($)){let A=$.to||"rpx.localhost";eF(A).forEach((J)=>w.add(J))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function K1($){if(Uw&&!$.forceRegenerate){G("ssl","Using cached SSL configuration",$.verbose);return}j6();let w=Kw($)?$.proxies.map((j)=>j.to):[$.to];G("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=l1($,$.verbose),J=A.basePath||O$(hY(),".stacks","ssl");await T$.mkdir(J,{recursive:!0});let Y=w9(J),U=await E6(Y,$.verbose),Z=!1;if(!U){if($.verbose)R.info("Generating Root CA certificate (one-time)...");U=await i8(A);try{await Promise.all([T$.writeFile(Y.caCertPath,U.certificate),T$.writeFile(Y.caKeyPath,U.privateKey,{mode:384})]),Z=!0,G("ssl",`Persisted Root CA at ${Y.caCertPath}`,$.verbose)}catch(j){throw G("ssl",`Error saving Root CA files: ${j}`,$.verbose),Error(`Failed to save Root CA files: ${j}`)}}else G("ssl",`Reusing existing Root CA from ${Y.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let B=await u8({...A,rootCA:{certificate:U.certificate,privateKey:U.privateKey}});try{await Promise.all([T$.writeFile(A.certPath,B.certificate),T$.writeFile(A.keyPath,B.privateKey),T$.writeFile(A.caCertPath,U.certificate)]),G("ssl","Certificate files saved successfully",$.verbose)}catch(j){throw G("ssl",`Error saving certificate files: ${j}`,$.verbose),Error(`Failed to save certificate files: ${j}`)}if(Z?!1:await Y9(Y.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(G("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(Uw={key:B.privateKey,cert:B.certificate,ca:U.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)R.info("Adding certificate to system trust store (may require sudo permission)...");let E=!1;if(Yw.platform==="darwin")try{kZ({caPath:Y.caCertPath,verbose:$.verbose});let j=qY();try{q1(`security add-trusted-cert ${T1} -k "${j}" "${Y.caCertPath}"`,{stdio:"ignore"})}catch{}if(d1(`security add-trusted-cert ${T1} -k ${H1} "${Y.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");E=!0;let F=O$(J,"trust-rpx-cert.sh"),f=`#!/bin/bash
|
|
178
178
|
echo "Trusting RPX Root CA"
|
|
179
|
-
sudo security add-trusted-cert ${
|
|
179
|
+
sudo security add-trusted-cert ${T1} -k ${H1} "${Y.caCertPath}"
|
|
180
180
|
echo "Root CA trusted! Please restart your browser."
|
|
181
181
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
182
|
-
`;await T$.writeFile(F,
|
|
182
|
+
`;await T$.writeFile(F,f,{mode:493})}catch(j){if($.verbose)R.warn(`Could not add Root CA to trust store automatically: ${j}`);let F=O$(J,"trust-rpx-cert.sh"),f=`#!/bin/bash
|
|
183
183
|
echo "Trusting RPX Root CA"
|
|
184
|
-
sudo security add-trusted-cert ${
|
|
184
|
+
sudo security add-trusted-cert ${T1} -k ${H1} "${Y.caCertPath}"
|
|
185
185
|
echo "Root CA trusted! Please restart your browser."
|
|
186
186
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
187
|
-
`;if(await T$.writeFile(F,
|
|
187
|
+
`;if(await T$.writeFile(F,f,{mode:493}),$.verbose)R.info(`Created a trust helper script at: ${F}`),R.info(`If you're still having certificate issues, run: sh ${F}`)}else if(Yw.platform==="linux")try{let{exec:j}=await import("node:child_process"),F="/usr/local/share/ca-certificates/rpx",f=`
|
|
188
188
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
189
|
-
cp "${
|
|
189
|
+
cp "${Y.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
190
190
|
update-ca-certificates
|
|
191
191
|
echo "RPX Root CA installed. Please restart your browser."
|
|
192
|
-
`,
|
|
193
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${
|
|
192
|
+
`,z=O$(bZ.tmpdir(),`rpx-trust-${Date.now()}.sh`);await T$.writeFile(z,f,{mode:493}),await new Promise((H)=>{j(`sudo bash "${z}"`,(T)=>{if(T){if($.verbose)R.warn(`Could not trust certificates: ${T}`);H(!1)}else{if($.verbose)R.success("Successfully added certificates to system trust store");H(!0)}})}),await T$.unlink(z).catch(()=>{}),E=!0}catch(j){if($.verbose)R.warn(`Failed to trust certificates: ${j}`)}else if(Yw.platform==="win32")try{let j=`
|
|
193
|
+
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${Y.caCertPath.replace(/\//g,"\\")}")
|
|
194
194
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
195
195
|
$store.Open("ReadWrite")
|
|
196
196
|
$store.Add($cert)
|
|
197
197
|
$store.Close()
|
|
198
198
|
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
|
|
199
|
+
`,F=O$(bZ.tmpdir(),"rpx-trust.ps1");if(await T$.writeFile(F,j),q1(`powershell -ExecutionPolicy Bypass -File "${F}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");E=!0}catch(j){if($.verbose)R.warn(`Could not trust certificate: ${j}`)}else try{await c8(B,U.certificate,A),E=!0}catch(j){if($.verbose)R.warn(`Could not add certificate to trust store: ${j}`)}if(Uw={key:B.privateKey,cert:B.certificate,ca:U.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!E&&$.verbose)R.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),R.warn("This will bypass the warning and you should only need to do it once")}function j6(){Uw=null}async function g0($){if(!$)return null;if(Uw)return Uw;let w=l1($);try{let[A,J,Y]=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 G("ssl",`Certificate files don't exist: key=${A}, cert=${J}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let U="regenerateUntrustedCerts"in $,Z=$.regenerateUntrustedCerts,B=U?Z!==!1:!0;G("ssl",`Trust check: hasFlag=${U}, flagValue=${Z}, shouldCheckTrust=${B}`,$.verbose);let W=w.basePath||O$(hY(),".stacks","ssl"),E=w9(W);if(!(B?await Y9(E.caCertPath,$):!0))return G("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[F,f,z]=await Promise.all([T$.readFile(w.keyPath,"utf8"),T$.readFile(w.certPath,"utf8"),Y&&w.caCertPath?T$.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(z&&!z.includes("-----BEGIN CERTIFICATE-----"))return G("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Kw($))try{let{X509Certificate:H}=await import("node:crypto"),q=new H(f).subjectAltName||"",h=$.proxies.map((I)=>I.to).filter((I)=>!q.includes(`DNS:${I}`));if(h.length>0)return G("ssl",`Certificate missing SANs for: ${h.join(", ")}, will regenerate`,$.verbose),null}catch(H){G("ssl",`Could not verify cert SANs: ${H}`,$.verbose)}return G("ssl","Successfully loaded existing certificates",$.verbose),Uw={key:F,cert:f,ca:z},Uw}catch(A){return G("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function l1($,w){let A=TY($);G("ssl",`Primary domain: ${A}`,w);let J=A9($),Y=O$(hY(),".stacks","ssl");if(typeof $.https==="object"){let U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:Y,Z={domain:A,hostCertCN:A,basePath:U,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($9($)).map((B)=>({type:2,value:B}))};if(OZ($.https.rootCA))Z.rootCA=$.https.rootCA;return Z}return{domain:A,hostCertCN:A,basePath:Y,...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($9($)).map((U)=>({type:2,value:U}))}}async function J9($,w){let A=A9({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];G("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((Y)=>_Z(Y,w)))}async function Y9($,w){try{if(G("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Yw.platform==="darwin"){if(w?.serverName)return xZ($,w.serverName,{verbose:w.verbose});return KY($,{verbose:w.verbose})}else if(Yw.platform==="win32")try{let J=q1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return G("ssl","Could not extract certificate subject",w?.verbose),!1;let Y=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${J}*' } | Select-Object Subject"`;if(q1(Y).toString().includes(J))return G("ssl","Certificate found in trusted root store",w?.verbose),!0;return G("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return G("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(Yw.platform==="linux")try{let J=q1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",Y=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let U of Y)try{if(q1(`find ${U} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return G("ssl",`Certificate fingerprint found in ${U}`,w?.verbose),!0}catch{}return G("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return G("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return G("ssl",`Platform ${Yw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return G("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var Uw=null,W6="rpx-root-ca.crt",B6="rpx-root-ca.key";var RY=h$(()=>{vj();o0();d8();PZ();U$();PZ();g8()});import*as U0 from"node:path";function p1($,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 z6($){let w=U0.extname($).toLowerCase();return F6[w]??"application/octet-stream"}function f6($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=U0.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function G6($,w){let A=f6($);if(A===null)return null;let J=U0.posix.extname(A);if(w.cleanUrls&&J===".html"){let Y=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:U0.join(w.dir,A),redirectTo:Y||"/"}}if(A===""||$.endsWith("/"))return{filePath:U0.join(w.dir,A,"index.html")};if(J!=="")return{filePath:U0.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:U0.join(w.dir,`${A}.html`)};return{filePath:U0.join(w.dir,A,"index.html")}}async function U9($,w){let A=G6($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let J=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",Y=Bun.file(A.filePath);if(await Y.exists())return new Response(Y,{status:200,headers:{"Content-Type":z6(A.filePath),"Cache-Control":J}});if(w.spa){let U=U0.join(w.dir,"index.html"),Z=Bun.file(U);if(await Z.exists())return new Response(Z,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var F6;var t1=h$(()=>{F6={".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 H6($){return($.headers.get("host")||"").split(":")[0]}function Z9($,w,A){let J=new URL($.url),Y=w.sourceHost??"",U=J.pathname,Z=XZ(J.pathname,w.pathRewrites);if(Z)Y=Z.targetHost,U=Z.targetPath,G("request",`Path rewrite: ${J.pathname} → ${Y}${U}`,A);return{targetHost:Y,targetPath:U,search:J.search}}function r1($,w){return async(A,J)=>{let Y=new URL(A.url),U=H6(A),Z=$(U);if(!Z)return G("request",`No route found for host: ${U}`,w),new Response(`No proxy configured for ${U}`,{status:404});if(Z.static)return U9(Y.pathname,Z.static);if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!J||!Z.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:F,targetPath:f,search:z}=Z9(A,Z,w),H=`ws://${F}${f}${z}`,T={};for(let[h,I]of A.headers)if(!T6.has(h.toLowerCase())&&h.toLowerCase()!=="host")T[h]=I;T.host=F,T["x-forwarded-for"]="127.0.0.1",T["x-forwarded-proto"]="https",T["x-forwarded-host"]=U;let q={targetUrl:H,forwardHeaders:T};if(J.upgrade(A,{data:q})){G("ws",`upgraded ${U}${f} → ${H}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!Z.sourceHost)return new Response(`No upstream configured for ${U}`,{status:502});let{targetHost:B,targetPath:W,search:E}=Z9(A,Z,w),j=`http://${B}${W}${E}`;try{let F=new Headers(A.headers);if(F.set("host",B),Z.changeOrigin)F.set("origin",`http://${Z.sourceHost}`);F.set("x-forwarded-for","127.0.0.1"),F.set("x-forwarded-proto","https"),F.set("x-forwarded-host",U);let f=await fetch(j,{method:A.method,headers:F,body:A.body,redirect:"manual"});if(Z.cleanUrls&&Y.pathname.endsWith(".html")){let H=Y.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H}})}let z=new Headers(f.headers);return new Response(f.body,{status:f.status,statusText:f.statusText,headers:z})}catch(F){return G("request",`Proxy error for ${U}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}}}function a1($){let w=new WeakMap;return{open(A){let{targetUrl:J,forwardHeaders:Y}=A.data,U;try{U=new WebSocket(J,{headers:Y})}catch(B){G("ws",`failed to open upstream ${J}: ${B}`,$),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let Z={upstream:U,upstreamOpen:!1,pending:[]};w.set(A,Z),U.addEventListener("open",()=>{Z.upstreamOpen=!0;for(let B of Z.pending)U.send(B);Z.pending=[]}),U.addEventListener("message",(B)=>{A.send(B.data)}),U.addEventListener("close",(B)=>{try{A.close(B.code||1000,B.reason||"")}catch{}}),U.addEventListener("error",()=>{G("ws",`upstream error for ${J}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,J){let Y=w.get(A);if(!Y)return;let U=typeof J==="string"?J:new Uint8Array(J);if(Y.upstreamOpen)Y.upstream.send(U);else Y.pending.push(U)},close(A,J,Y){let U=w.get(A);if(!U)return;w.delete(A);try{U.upstream.close(J||1000,Y||"")}catch{}}}}var T6;var NY=h$(()=>{t1();U$();T6=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function MY($){return $.startsWith("*.")}function K6($,w){if(!MY(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function s1($,w){let A=$.get(w);if(A!==void 0)return A;let J,Y=-1;for(let[U,Z]of $){if(!MY(U))continue;if(K6(w,U)){let B=U.length-1;if(B>Y)Y=B,J=Z}}return J}import*as o1 from"node:fs/promises";import*as iZ from"node:path";function h6($){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 R6($,w,A,J){try{let[Y,U]=await Promise.all([o1.readFile(w,"utf8"),o1.readFile(A,"utf8")]);return{serverName:$,cert:Y,key:U}}catch(Y){return G("sni",`skipping ${$}: ${Y.message}`,J),null}}async function uZ($,w){let A=new Map;if($.certsDir){let Y=[];try{Y=await o1.readdir($.certsDir)}catch(U){G("sni",`certsDir read failed (${$.certsDir}): ${U.message}`,w)}for(let U of Y){let Z=h6(U);if(!Z)continue;let B=U.slice(0,-4);A.set(Z,{certPath:iZ.join($.certsDir,U),keyPath:iZ.join($.certsDir,`${B}.key`)})}}if($.domains)for(let[Y,U]of Object.entries($.domains))A.set(Y,U);let J=[];for(let[Y,U]of A){let Z=await R6(Y,U.certPath,U.keyPath,w);if(Z)J.push(Z)}return J}var cZ=h$(()=>{U$()});import*as IY from"node:fs";import*as i$ from"node:fs/promises";import{homedir as N6}from"node:os";import*as vZ from"node:path";import*as CY from"node:process";function Zw(){return vZ.join(N6(),".stacks","rpx","registry.d")}function e1($){return typeof $==="string"&&$.length>0&&$.length<=128&&M6.test($)}function mZ($,w){if(!e1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return vZ.join($,`${w}.json`)}function m$($){if(!Number.isInteger($)||$<=0)return!1;try{return CY.kill($,0),!0}catch(w){return w.code==="EPERM"}}function W9($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,J=typeof w.from==="string"&&w.from.length>0,Y=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string";return typeof w.id==="string"&&e1(w.id)&&(J||Y)&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function I6($){await i$.mkdir($,{recursive:!0})}async function B9($,w=Zw(),A){if(!W9($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await I6(w);let J=mZ(w,$.id),Y=`${J}.tmp.${CY.pid}.${Date.now()}`,U=JSON.stringify($,null,2);try{await i$.writeFile(Y,U,{encoding:"utf8",mode:420}),await i$.rename(Y,J),G("registry",`wrote entry ${$.id} → ${J}`,A)}catch(Z){throw await i$.unlink(Y).catch(()=>{}),Z}}async function nZ($,w=Zw(),A){let J=mZ(w,$);try{await i$.unlink(J),G("registry",`removed entry ${$}`,A)}catch(Y){if(Y.code!=="ENOENT")throw Y}}async function C6($,w=Zw(),A){let J=mZ(w,$);try{let Y=await i$.readFile(J,"utf8"),U=JSON.parse(Y);if(!W9(U))return G("registry",`entry ${$} failed validation, removing`,A),await i$.unlink(J).catch(()=>{}),null;return U}catch(Y){if(Y.code==="ENOENT")return null;if(Y instanceof SyntaxError)return G("registry",`entry ${$} has invalid JSON, removing`,A),await i$.unlink(J).catch(()=>{}),null;throw Y}}async function hw($=Zw(),w){let A;try{A=await i$.readdir($)}catch(Y){if(Y.code==="ENOENT")return[];throw Y}let J=[];for(let Y of A){if(!Y.endsWith(".json"))continue;let U=Y.slice(0,-5);if(!e1(U))continue;let Z=await C6(U,$,w);if(Z)J.push(Z)}return J}async function LY($=Zw(),w){let A=await hw($,w),J=0;for(let Y of A){if(Y.pid===void 0)continue;if(!m$(Y.pid))G("registry",`GC: pid ${Y.pid} for ${Y.id} is dead, removing`,w),await nZ(Y.id,$,w).catch(()=>{}),J++}return J}function dZ($,w={}){let A=w.dir??Zw(),J=w.debounceMs??100,Y=w.pollMs??Math.max(J*2,250),U=w.verbose;IY.mkdirSync(A,{recursive:!0});let Z=null,B=!1,W=null,E=!1,j=(q)=>{return JSON.stringify(q.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,h)=>K.id.localeCompare(h.id)))},F=()=>{if(Z=null,B)return;hw(A,U).then((q)=>{return W=j(q),$(q)}).catch((q)=>{G("registry",`watcher onChange failed: ${q}`,U)})},f=()=>{if(B)return;if(Z)clearTimeout(Z);Z=setTimeout(F,J)},H=setInterval(()=>{if(B||E)return;E=!0,hw(A,U).then((q)=>{if(j(q)!==W)f()}).catch((q)=>{G("registry",`watcher poll failed: ${q}`,U)}).finally(()=>{E=!1})},Y),T=IY.watch(A,{persistent:!0},(q,K)=>{if(K&&/\.tmp\.\d+\.\d+$/.test(K))return;f()});return T.on("error",(q)=>{G("registry",`watcher error: ${q}`,U)}),f(),{close:()=>{if(B=!0,Z)clearTimeout(Z);clearInterval(H),T.close()}}}var M6;var $A=h$(()=>{U$();M6=/^[a-zA-Z0-9._-]+$/});import{spawn as L6}from"node:child_process";import*as Rw from"node:fs/promises";import{homedir as y6}from"node:os";import*as wA from"node:path";import*as u$ from"node:process";function l0(){return wA.join(y6(),".stacks","rpx")}function j9($=l0()){return wA.join($,"daemon.pid")}async function E9($=l0()){try{let w=await Rw.readFile(j9($),"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 V6($=l0()){await Rw.unlink(j9($)).catch(()=>{})}function S6(){let $=u$.execPath,w=wA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&u$.argv[1])return[$,u$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function F9($={}){let w=$.rpxDir??l0(),A=$.verbose??!1;await Ww({rpxDir:w,verbose:A}).catch((j)=>{G("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,A)});let J=await E9(w);if(J!==null&&m$(J))return G("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)G("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await V6(w);await Rw.mkdir(w,{recursive:!0});let Y=$.spawnCommand??S6();if(Y.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");G("daemon",`spawning daemon: ${Y.join(" ")}`,A);let U=L6(Y[0],Y.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??u$.cwd(),env:$.spawnEnv?{...u$.env,...$.spawnEnv}:u$.env});U.unref();let Z=null;U.once("error",(j)=>{Z=j});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,E=Date.now()+B;while(Date.now()<E){if(Z)throw Z;let j=await E9(w);if(j!==null&&m$(j))return G("daemon",`daemon registered with pid=${j}`,A),{pid:j,spawned:!0};await new Promise((F)=>setTimeout(F,W))}if(Z)throw Z;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}var gZ=h$(()=>{o0();RY();NY();cZ();t1();$A();h1();U$()});import*as Bw from"node:fs/promises";import{homedir as O6}from"node:os";import*as lZ from"node:path";function f9(){return lZ.join(O6(),".stacks","rpx")}function pZ($=f9()){return lZ.join($,X6)}async function VY($=f9()){try{let w=await Bw.readFile(pZ($),"utf8"),A=JSON.parse(w);if(A.version!==yY||!Array.isArray(A.resolvers))return null;return{version:yY,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 G9($,w){await Bw.mkdir($,{recursive:!0}),await Bw.writeFile(pZ($),`${JSON.stringify(w,null,2)}
|
|
200
|
+
`,"utf8")}async function tZ($){await Bw.rm(pZ($),{force:!0})}function T9($){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 _6($){let w=T9($);if(!w)return null;let A=w.split(".");if(A.length<2)return null;return A.slice(-2).join(".")}function rZ($){let w=new Set;for(let A of $){let J=_6(A);if(J)w.add(J)}return Array.from(w).sort()}function aZ($){let w=new Set;for(let A of $){let J=T9(A);if(J)w.add(J)}return Array.from(w).sort()}var yY=1,X6="dns-state.json",z9;var H9=h$(()=>{z9=["com","test","dev","app","page","local","localhost","example","invalid"]});var _Y={};TW(_Y,{tearDownDevelopmentDns:()=>Nw,syncDevelopmentDnsFromRegistry:()=>AA,stopDnsServer:()=>sZ,startDnsServer:()=>M9,setupResolver:()=>m6,setupDevelopmentDns:()=>wW,resolverFilePath:()=>R1,removeResolver:()=>d6,removeLegacyTldResolvers:()=>$W,reconcileStaleDevelopmentDns:()=>Ww,isDnsServerRunning:()=>b6,contentLooksLikeRpxResolver:()=>I9,RPX_RESOLVER_MARKER:()=>h9,DNS_PORT:()=>XY});import D6 from"node:dgram";import*as q9 from"node:fs/promises";import*as K9 from"node:path";import*as p0 from"node:process";function Q6($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function N9($,w){let A=[],J=w;while(!0){let Y=$[J];if(Y===0){J++;break}if((Y&192)===192){let U=$.readUInt16BE(J)&16383,{name:Z}=N9($,U);A.push(Z),J+=2;break}J++,A.push($.subarray(J,J+Y).toString("ascii")),J+=Y}return{name:A.join("."),newOffset:J}}function k6($,w){let{name:A,newOffset:J}=N9($,w),Y=$.readUInt16BE(J),U=$.readUInt16BE(J+2);return{question:{name:A,type:Y,class:U},newOffset:J+4}}function OY($){let w=$.split("."),A=[];for(let J of w)A.push(Buffer.from([J.length])),A.push(Buffer.from(J,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function x6($,w,A){let J=[],Y=Buffer.alloc(12);Y.writeUInt16BE($,0),Y.writeUInt16BE(33152,2),Y.writeUInt16BE(1,4),Y.writeUInt16BE(1,6),Y.writeUInt16BE(0,8),Y.writeUInt16BE(0,10),J.push(Y),J.push(OY(w.name));let U=Buffer.alloc(4);U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),J.push(U),J.push(OY(w.name));let Z=Buffer.alloc(10);if(Z.writeUInt16BE(w.type,0),Z.writeUInt16BE(1,2),Z.writeUInt32BE(300,4),w.type===1){Z.writeUInt16BE(4,8),J.push(Z);let B=A.split(".").map((W)=>Number.parseInt(W,10));J.push(Buffer.from(B))}else if(w.type===28)Z.writeUInt16BE(16,8),J.push(Z),J.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return Y.writeUInt16BE(33155,2),Y.writeUInt16BE(0,6),Buffer.concat([Y,OY(w.name),U]);return Buffer.concat(J)}function P6($,w){let A=[],J=Buffer.alloc(12);J.writeUInt16BE($,0),J.writeUInt16BE(33155,2),J.writeUInt16BE(1,4),J.writeUInt16BE(0,6),J.writeUInt16BE(0,8),J.writeUInt16BE(0,10),A.push(J),A.push(OY(w.name));let Y=Buffer.alloc(4);return Y.writeUInt16BE(w.type,0),Y.writeUInt16BE(w.class,2),A.push(Y),Buffer.concat(A)}async function M9($,w){if(p0.platform!=="darwin")return!1;let A=aZ($);if(A.length===0)return!1;if(n$){for(let J of A)SY.add(J);return G("dns","DNS server already running — merged domains",w),!0}return SY=new Set(A),new Promise((J)=>{n$=D6.createSocket("udp4"),n$.on("error",(Y)=>{G("dns",`DNS server error: ${Y.message}`,w),n$?.close(),n$=null,J(!1)}),n$.on("message",(Y,U)=>{try{let Z=Q6(Y),{question:B}=k6(Y,12);G("dns",`Query for ${B.name} type ${B.type} from ${U.address}`,w);let W=B.name.toLowerCase(),E=!1;for(let F of SY)if(W===F||W.endsWith(`.${F}`)){E=!0;break}let j;if(E&&(B.type===1||B.type===28))j=x6(Z.id,B,"127.0.0.1"),G("dns",`Responding with localhost for ${B.name}`,w);else j=P6(Z.id,B),G("dns",`NXDOMAIN for ${B.name}`,w);n$?.send(j,U.port,U.address)}catch(Z){G("dns",`Error processing DNS query: ${Z}`,w)}}),n$.on("listening",()=>{let Y=n$?.address();G("dns",`DNS server listening on ${Y?.address}:${Y?.port}`,w),J(!0)});try{n$.bind(XY,"127.0.0.1")}catch(Y){G("dns",`Failed to bind DNS server: ${Y}`,w),J(!1)}})}function sZ($){if(n$)G("dns","Stopping DNS server",$),n$.close(),n$=null,SY=new Set}function b6(){return n$!==null}function i6(){return`${h9}
|
|
201
201
|
nameserver 127.0.0.1
|
|
202
|
-
port ${
|
|
203
|
-
`}function
|
|
202
|
+
port ${XY}
|
|
203
|
+
`}function R1($){return K9.join(R9,$)}function I9($){return $.includes("127.0.0.1")&&$.includes(String(XY))}async function u6($){try{return await q9.readFile(R1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function oZ($){if(p0.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (U$(),G1));if(!A()){G("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),G("dns","DNS cache flushed",$)}catch(J){G("dns",`Could not flush DNS cache: ${J}`,$)}}async function c6($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (U$(),G1)),J=i6().replace(/\n/g,"\\n"),Y=`bash -c 'mkdir -p ${R9} && printf "%b" "${J}" > ${R1($)}'`;A(Y),G("dns",`Created ${R1($)}`,w)}async function v6($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (U$(),G1));A(`rm -f ${R1($)}`),G("dns",`Removed ${R1($)}`,w)}async function m6($,w){return wW({domains:w??[],verbose:$})}async function n6($,w){if(p0.platform!=="darwin")return!0;let{getSudoPassword:A}=await Promise.resolve().then(() => (U$(),G1));if(!A())return G("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let J of $)await c6(J,w);return await oZ(w),!0}catch(J){return G("dns",`Failed to create resolver file: ${J}`,w),!1}}async function eZ($,w){if(p0.platform!=="darwin")return;let{getSudoPassword:A}=await Promise.resolve().then(() => (U$(),G1));if(!A())return;try{for(let J of $)await v6(J,w);await oZ(w)}catch(J){G("dns",`Failed to remove resolver files: ${J}`,w)}}async function $W($){if(p0.platform!=="darwin")return[];let w=[];for(let A of z9){let J=await u6(A);if(J&&I9(J))await eZ([A],$),w.push(A)}return w}async function wW($){let w=$.rpxDir??l0(),A=aZ($.domains);if(A.length===0)return!1;let J=rZ(A);if(!await M9(A,$.verbose))return!1;if(!await n6(J,$.verbose))return!1;let Z={version:yY,resolvers:J,domains:A,ownerPid:$.ownerPid??p0.pid,updatedAt:new Date().toISOString()};return await G9(w,Z),!0}async function AA($,w={}){let A=$.map((W)=>W.to).filter(Boolean),J=w.rpxDir??l0(),Y=rZ(A),B=((await VY(J))?.resolvers??[]).filter((W)=>!Y.includes(W));if(B.length>0)await eZ(B,w.verbose);if(Y.length===0){sZ(w.verbose),await tZ(J);return}await wW({domains:A,rpxDir:J,verbose:w.verbose,ownerPid:w.ownerPid??p0.pid})}async function Nw($={}){let w=$.rpxDir??l0();sZ($.verbose);let J=(await VY(w))?.resolvers??[];await eZ(J,$.verbose),await $W($.verbose),await tZ(w)}async function d6($){await Nw({verbose:$})}async function Ww($={}){let w=$.rpxDir??l0(),A=await VY(w),J=A?.ownerPid!=null&&m$(A.ownerPid);if(A&&!J){G("dns",`reconcile: owner pid ${A.ownerPid} is gone — tearing down DNS`,$.verbose),await Nw($);return}let Y=await $W($.verbose);if(Y.length>0)G("dns",`reconcile: removed legacy TLD resolvers: ${Y.join(", ")}`,$.verbose);await oZ($.verbose)}var XY=15353,h9="# managed-by: rpx",R9="/etc/resolver",n$=null,SY;var h1=h$(()=>{gZ();H9();$A();U$();SY=new Set});import{dirname as fq,join as Gq}from"path";import*as v$ from"process";import{fileURLToPath as Tq}from"url";import{existsSync as e9}from"node:fs";import nY from"node:fs/promises";import HW from"node:os";import dY from"node:path";import zw from"node:process";import{EventEmitter as $z}from"node:events";import t0 from"node:process";import qW from"node:process";import tY from"node:process";import FA from"node:process";import L1 from"node:process";import RW from"node:tty";import vz,{stdin as xq,stdout as Pq}from"node:process";import MW,{stdin as dz,stdout as gz}from"node:process";import lz from"node:readline";class CW{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=HW.homedir(),w=dY.join($,".config","clapp");this.configPath=dY.join(w,"telemetry.json")}async isEnabled(){if(zw.env.DO_NOT_TRACK==="1"||zw.env.DO_NOT_TRACK==="true")return!1;if(zw.env.NO_TELEMETRY==="1"||zw.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 J={event:$,...w,timestamp:Date.now(),platform:HW.platform(),nodeVersion:zw.version};if(this.events.push(J),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:zw.env.DO_NOT_TRACK==="1"||zw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(e9(this.configPath)){let $=await nY.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=dY.dirname(this.configPath);await nY.mkdir(w,{recursive:!0}),await nY.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 Iq=new CW;function wz($,w={}){let A={_:[]},J=w.alias||{},Y=new Set(w.boolean||[]),U={};for(let B of Object.keys(J))for(let W of J[B])U[W]=B;for(let B of Y)if(J[B])for(let W of J[B])Y.add(W);function Z(B,W){let E=U[B]||B;if(A[E]=W,J[E])for(let j of J[E])A[j]=W;if(U[B]&&J[U[B]])for(let j of J[U[B]])A[j]=W;A[B]=W}for(let B=0;B<$.length;B++){let W=$[B];if(W==="--"){A._.push(...$.slice(B+1));break}if(W.startsWith("--")){let E=W.indexOf("=");if(E!==-1){let j=W.slice(2,E),F=W.slice(E+1);Z(j,F)}else{let j=W.slice(2);if(j.startsWith("no-")){let f=j.slice(3);Z(f,!1);continue}let F=U[j]||j;if(Y.has(F)||Y.has(j))Z(j,!0);else{let f=$[B+1];if(f!==void 0&&!f.startsWith("-"))Z(j,f),B++;else Z(j,!0)}}}else if(W.startsWith("-")&&W.length>1){let E=W.slice(1);for(let j=0;j<E.length;j++){let F=E[j],f=U[F]||F;if(j===E.length-1&&!Y.has(f)&&!Y.has(F)){let z=$[B+1];if(z!==void 0&&!z.startsWith("-"))Z(F,z),B++;else Z(F,!0)}else Z(F,!0)}}else A._.push(W)}return A}function pY($){return $.replace(/[<[].+/,"").trim()}function Az($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,J=[],Y=(B)=>{let W=!1,E=B[1];if(E.startsWith("..."))E=E.slice(3),W=!0;return{required:B[0].startsWith("<"),value:E,variadic:W}},U;while(U=w.exec($))J.push(Y(U));let Z;while(Z=A.exec($))J.push(Y(Z));return J}function Jz($){let w={alias:{},boolean:[]};for(let[A,J]of $.entries()){if(J.names.length>1)w.alias[J.names[0]]=J.names.slice(1);if(J.isBoolean)if(J.negated){if(!$.some((U,Z)=>{return Z!==A&&U.names.some((B)=>J.names.includes(B))&&typeof U.required==="boolean"}))w.boolean.push(J.names[0])}else w.boolean.push(J.names[0])}return w}function KW($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function gY($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function Yz($){return $.replace(/([a-z])-([a-z])/g,(w,A,J)=>{return A+J.toUpperCase()})}function Uz($,w,A){let J=0,Y=w.length,U=$,Z;for(;J<Y;++J)Z=U[w[J]],U=U[w[J]]=J===Y-1?A:Z!=null?Z:!!~w[J+1].indexOf(".")||!(+w[J+1]>-1)?{}:[]}function Zz($,w){for(let A of Object.keys(w)){let J=w[A];if(J.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof J.transformFunction==="function")$[A]=$[A].map(J.transformFunction)}}}function Wz($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function LW($){return $.split(".").map((w,A)=>{return A===0?Yz(w):w}).join(".")}class jA 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
204
|
|
|
205
205
|
Stack trace:
|
|
206
|
-
${this.stack}`;return this.message}}function
|
|
207
|
-
`);let
|
|
206
|
+
${this.stack}`;return this.message}}function Bz(){let{env:$}=qW,{TERM:w,TERM_PROGRAM:A}=$;if(qW.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 GA="\x1B",J$=`${GA}[`;var I0={to($,w){if(!w)return`${J$}${$+1}G`;return`${J$}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${J$}${-$}D`;else if($>0)A+=`${J$}${$}C`;if(w<0)A+=`${J$}${-w}A`;else if(w>0)A+=`${J$}${w}B`;return A},up:($=1)=>`${J$}${$}A`,down:($=1)=>`${J$}${$}B`,forward:($=1)=>`${J$}${$}C`,backward:($=1)=>`${J$}${$}D`,nextLine:($=1)=>`${J$}E`.repeat($),prevLine:($=1)=>`${J$}F`.repeat($),left:`${J$}G`,hide:`${J$}?25l`,show:`${J$}?25h`,save:`${GA}7`,restore:`${GA}8`};var lY={screen:`${J$}2J`,up:($=1)=>`${J$}1J`.repeat($),down:($=1)=>`${J$}J`.repeat($),line:`${J$}2K`,lineEnd:`${J$}K`,lineStart:`${J$}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?I0.up():"");if($)w+=I0.left;return w}},Vq={screen:`${GA}c`};function Ez($,w){let A=[];for(let J=0;J<=w.length;J++)A[J]=[J];for(let J=0;J<=$.length;J++)A[0][J]=J;for(let J=1;J<=w.length;J++)for(let Y=1;Y<=$.length;Y++)if(w.charAt(J-1)===$.charAt(Y-1))A[J][Y]=A[J-1][Y-1];else A[J][Y]=Math.min(A[J-1][Y-1]+1,A[J][Y-1]+1,A[J-1][Y]+1);return A[w.length][$.length]}function yW($,w,A=2,J=3){return w.map((Y)=>({cmd:Y,distance:Ez($,Y)})).filter(({distance:Y})=>Y<=A).sort((Y,U)=>Y.distance-U.distance).slice(0,J).map(({cmd:Y})=>Y)}class VW{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=pY($).split(",").map((J)=>{let Y=J.trim().replace(/^-{1,2}/,"");if(Y.startsWith("no-"))this.negated=!0,Y=Y.replace(/^no-/,"");return LW(Y)}).sort((J,Y)=>J.length>Y.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 Oq=tY.argv,jz=`${tY.platform}-${tY.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,hW=FA.argv,Fz=`${FA.platform}-${FA.arch} node-${FA.version}`;class rY{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,A,J){this.rawName=$,this.description=w,this.config=A,this.cli=J,this.options=[],this.aliasNames=[],this.name=pY($);let Y=pY($),U=Y.indexOf(":");if(U>0)this.namespace=Y.substring(0,U),this.name=Y.substring(U+1);if(this.args=Az($),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 J=new VW($,w,A);return this.options.push(J),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 aY}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:J,helpCallback:Y}=this.cli.globalCommand,U=[{body:`${$}${A?`/${A}`:""}`}];if(U.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let W=KW(w.map((z)=>z.rawName)),E=new Map,j=[];for(let z of w)if(z.namespace){if(!E.has(z.namespace))E.set(z.namespace,[]);E.get(z.namespace).push(z)}else j.push(z);let F="";if(j.length>0)F+=j.map((z)=>{return` ${gY(z.rawName,W.length)} ${z.description}`}).join(`
|
|
207
|
+
`);let f=Array.from(E.keys()).sort();for(let z of f){let H=E.get(z);if(F.length>0)F+=`
|
|
208
208
|
|
|
209
|
-
`;F+=` ${
|
|
210
|
-
`,F+=
|
|
211
|
-
`)}
|
|
212
|
-
`)})}let
|
|
213
|
-
`)})}if(this.examples.length>0)
|
|
214
|
-
`)});if(U
|
|
215
|
-
${
|
|
209
|
+
`;F+=` ${z}:
|
|
210
|
+
`,F+=H.map((T)=>{return` ${gY(T.rawName,W.length-2)} ${T.description}`}).join(`
|
|
211
|
+
`)}U.push({title:"Commands",body:F}),U.push({title:"For more info, run any command with the `--help` flag",body:w.map((z)=>` $ ${$}${z.displayName===""?"":` ${z.displayName}`} --help`).join(`
|
|
212
|
+
`)})}let B=this.isGlobalCommand?J:[...this.options,...J||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)B=B.filter((W)=>W.name!=="version");if(B.length>0){let W=KW(B.map((E)=>E.rawName));U.push({title:"Options",body:B.map((E)=>{return` ${gY(E.rawName,W.length)} ${E.description} ${E.config.default===void 0?"":`(default: ${E.config.default})`}`}).join(`
|
|
213
|
+
`)})}if(this.examples.length>0)U.push({title:"Examples",body:this.examples.map((W)=>{if(typeof W==="function")return W($);return W}).join(`
|
|
214
|
+
`)});if(Y)U=Y(U)||U;console.log(U.map((W)=>{return W.title?`${W.title}:
|
|
215
|
+
${W.body}`:W.body}).join(`
|
|
216
216
|
|
|
217
|
-
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?
|
|
217
|
+
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?jz:Fz}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((Y)=>Y.required).slice(this.cli.args.length),J=A.map((Y)=>`<${Y.value}>`).join(" ");throw new jA(`Missing required argument${A.length>1?"s":""}: ${J}
|
|
218
218
|
|
|
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
|
|
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 Y=[...w.options,...this.options].flatMap((W)=>W.names),U=A.length>1?`--${A}`:`-${A}`,Z=yW(A,Y),B=`Unknown option \`${U}\``;if(Z.length>0)B+=`
|
|
220
220
|
|
|
221
|
-
Did you mean one of these?`,
|
|
222
|
-
• ${
|
|
221
|
+
Did you mean one of these?`,Z.forEach((W)=>{let E=W.length>1?`--${W}`:`-${W}`;B+=`
|
|
222
|
+
• ${E}`});throw B+=`
|
|
223
223
|
|
|
224
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
224
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new jA(B)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let J of A){let Y=$[J.name.split(".")[0]];if(J.required){let U=A.some((Z)=>Z.negated&&Z.names.includes(J.name));if(Y===!0||Y===!1&&!U)throw new jA(`Option \`${J.rawName}\` requires a value.
|
|
225
225
|
|
|
226
|
-
Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class
|
|
226
|
+
Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class aY extends rY{constructor($){super("@@global@@","",{},$)}}var zz=rY,r0={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 I1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function fz(){return!0}function Gz(){let $={};$.supportsColor=fz();function w(J,Y=[]){let U=J===""?[]:[...Y,J],Z=function(W){if(!$.supportsColor)return W;let E="",j="";for(let F of U)if(F in I1&&I1[F]in r0){let f=I1[F];E+=r0[f][0],j=r0[f][1]+j}else if(F in r0)E+=r0[F][0],j=r0[F][1]+j;return E+W+j},B=[...Object.keys(r0),...Object.keys(I1)];for(let W of B)if(!(W in Z))Object.defineProperty(Z,W,{get(){return w(W,U)}});return Z}let A=[...Object.keys(r0),...Object.keys(I1)];for(let J of A)if(!(J in $))Object.defineProperty($,J,{get(){return w(J)}});return $}var C1=Gz();class sY extends $z{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 aY(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(A)=>{if(console.log(`
|
|
227
227
|
|
|
228
|
-
Received ${A}, cleaning up...`),$)try{await $()}catch(J){console.error("Error during cleanup:",J)}
|
|
228
|
+
Received ${A}, cleaning up...`),$)try{await $()}catch(J){console.error("Error during cleanup:",J)}t0.exit(0)};return t0.on("SIGINT",()=>w("SIGINT")),t0.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 J=new zz($,w||"",A,this);return J.globalCommand=this.globalCommand,this.commands.push(J),J}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,J){if(this.args=$,this.options=w,A)this.matchedCommand=A;if(J)this.matchedCommandName=J;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(C1.red(`
|
|
229
229
|
✗ Command "${$}" not found.
|
|
230
|
-
`)),this.enableDidYouMean){let w=[];for(let J of this.commands){if(J.displayName)w.push(J.displayName);if(J.aliasNames)w.push(...J.aliasNames)}let A=
|
|
231
|
-
Run \`${this.name??"cli"} --help\` for usage.`;
|
|
232
|
-
`),
|
|
230
|
+
`)),this.enableDidYouMean){let w=[];for(let J of this.commands){if(J.displayName)w.push(J.displayName);if(J.aliasNames)w.push(...J.aliasNames)}let A=yW($,w);if(A.length>0)console.log(C1.yellow("Did you mean one of these?")),A.forEach((J)=>console.log(` ${C1.dim("•")} ${this.name} ${J}`)),console.log("")}console.log(C1.dim("Run"),`${this.name} --help`,C1.dim("to see all available commands")),t0.exit(1)}async parse($=hW,w={}){let{run:A=!0,exitOnError:J=!1}=w;if(J)try{return await this.parse($,{run:A})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=$,!this.name)this.name=$[1]?Wz($[1]):"cli";let Y=!0,U=$.slice(2),Z=U[0];if(Z&&!Z.startsWith("-")){for(let W of this.commands)if(W.isMatched(Z)){let E=this.mri(U,W);Y=!1;let j={...E,args:E.args.slice(1)};this.setParsedInfo(j,W,Z),this.emit(`command:${Z}`,W);break}}if(Y){for(let W of this.commands)if(W.name===""){Y=!1;let E=this.mri(U,W);this.setParsedInfo(E,W),this.emit("command:!",W);break}}if(Y){let W=this.mri($.slice(2));this.setParsedInfo(W)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),A=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),A=!1,this.unsetMatchedCommand();let B={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 B}mri($,w){let A=[...this.globalCommand.options,...w?w.options:[]],J=Jz(A),Y=[],U=$.indexOf("--");if(U>-1)Y=$.slice(U+1),$=$.slice(0,U);let Z=wz($,J),B={_:Z._};for(let f of Object.keys(Z))if(f!=="_")B[LW(f)]=Z[f];let W=B._,E={"--":Y},j=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,F=Object.create(null);for(let f of A){if(!j&&f.config.default!==void 0)for(let z of f.names)E[z]=f.config.default;if(Array.isArray(f.config.type)){if(F[f.name]===void 0)F[f.name]={shouldTransform:!0,transformFunction:f.config.type[0]}}}for(let f of Object.keys(B))if(f!=="_"){let z=f.split(".");Uz(E,z,B[f]),Zz(E,F)}return{args:W,options:E}}async run($=hW){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let J=$,Y=J.message??"command-line error",U=this.name?`${this.name}: `:"",Z=/--help/.test(Y)?"":`
|
|
231
|
+
Run \`${this.name??"cli"} --help\` for usage.`;t0.stderr.write(`${U}${Y}${Z}
|
|
232
|
+
`),t0.exit(J.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let J=[];A.args.forEach((B,W)=>{if(B.variadic)J.push($.slice(W));else J.push($[W])}),J.push(w);let Y={command:A,args:J,options:w};for(let B of A.beforeHooks)await B(Y);let U,Z=async()=>{let B=A.commandAction.apply(this,J);if(B instanceof Promise)U=await B;else U=B;return U};if(A.middleware.length>0){let B=0,W=async()=>{if(B<A.middleware.length){let E=A.middleware[B++];await E({...Y,next:W})}else await Z()};await W()}else await Z();for(let B of A.afterHooks)await B(Y);return U}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return t0.removeAllListeners("SIGINT"),t0.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 SW{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 _q=new SW;function Tz(){if("FORCE_COLOR"in L1.env)return L1.env.FORCE_COLOR!=="0";if("NO_COLOR"in L1.env||L1.env.TERM==="dumb")return!1;if(L1.platform==="win32")return!0;return RW.isatty(1)&&RW.isatty(2)}var OW=Tz();function o($,w){if(!OW)return(A)=>A;return(A)=>$+A+w}var Hz=o("\x1B[0m","\x1B[0m"),qz=o("\x1B[31m","\x1B[39m"),Kz=o("\x1B[32m","\x1B[39m"),hz=o("\x1B[33m","\x1B[39m"),Rz=o("\x1B[34m","\x1B[39m"),Nz=o("\x1B[35m","\x1B[39m"),Mz=o("\x1B[36m","\x1B[39m"),Iz=o("\x1B[37m","\x1B[39m"),Cz=o("\x1B[90m","\x1B[39m"),Lz=o("\x1B[1m","\x1B[22m"),yz=o("\x1B[3m","\x1B[23m"),Vz=o("\x1B[4m","\x1B[24m"),Sz=o("\x1B[2m","\x1B[22m"),Oz=o("\x1B[7m","\x1B[27m"),Xz=o("\x1B[8m","\x1B[28m"),_z=o("\x1B[9m","\x1B[29m"),Dz=o("\x1B[41m","\x1B[49m"),Qz=o("\x1B[42m","\x1B[49m"),kz=o("\x1B[43m","\x1B[49m"),xz=o("\x1B[44m","\x1B[49m"),Pz=o("\x1B[45m","\x1B[49m"),bz=o("\x1B[46m","\x1B[49m"),iz=o("\x1B[47m","\x1B[49m"),uz=OW,cz={reset:Hz,red:qz,green:Kz,yellow:hz,blue:Rz,magenta:Nz,cyan:Mz,white:Iz,gray:Cz,bold:Lz,italic:yz,underline:Vz,dim:Sz,inverse:Oz,hidden:Xz,strikethrough:_z,bgRed:Dz,bgGreen:Qz,bgYellow:kz,bgBlue:xz,bgMagenta:Pz,bgCyan:bz,bgWhite:iz,isColorSupported:uz},zA=cz,mz=["up","down","left","right","space","enter","cancel"],fA={actions:new Set(mz),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function XW($,w){if(typeof $==="string")return fA.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(XW(A,w))return!0}return!1}function nz($,w){if($===w)return[];let A=$.split(`
|
|
233
233
|
`),J=w.split(`
|
|
234
|
-
`),
|
|
235
|
-
`),
|
|
236
|
-
`)}class
|
|
237
|
-
`),
|
|
238
|
-
`).length-1;this.output.write(
|
|
239
|
-
`);this.output.write(J[A]),this._prevFrame=$,this.output.write(
|
|
240
|
-
`).slice(A);this.output.write(
|
|
241
|
-
`)),this._prevFrame=$;return}this.output.write(
|
|
242
|
-
`)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=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
|
+
`),Y=[];for(let U=0;U<Math.max(A.length,J.length);U++)if(A[U]!==J[U])Y.push(U);return Y}var bq=vz.platform.startsWith("win"),NW=Symbol("clapp:cancel");function EA($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function pz($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function tz($){return pz($).length}function IW($,w,A){if(!w||w<1)return $;let J=A?.hard??!1,Y=A?.trim??!0,U=$.split(`
|
|
235
|
+
`),Z=[];for(let B of U){if(tz(B)<=w){Z.push(Y?B.trimEnd():B);continue}if(J){let W="",E=0,j=0;while(j<B.length){let F=B.slice(j).match(/^\x1b\[[0-9;]*m/);if(F){W+=F[0],j+=F[0].length;continue}if(E>=w)Z.push(Y?W.trimEnd():W),W="",E=0;W+=B[j],E++,j++}if(W)Z.push(Y?W.trimEnd():W)}else Z.push(Y?B.trimEnd():B)}return Z.join(`
|
|
236
|
+
`)}class oY{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=dz,output:J=gz,render:Y,signal:U,...Z}=$;this.opts=Z,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Y.bind(this),this._track=w,this._abortSignal=U,this.input=A,this.output=J}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($)??[],J=[];for(let Y of A)if(Y.cb(...w),Y.once)J.push(()=>A.splice(A.indexOf(Y),1));for(let Y of J)Y();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(NW);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=lz.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),EA(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),EA(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(I0.show),this.output.off("resize",this.render),EA(this.input,!1),$(NW)})})}_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 J=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(J)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&fA.aliases.has(w.name))this.emit("cursor",fA.aliases.get(w.name));if(fA.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(XW([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
237
|
+
`),EA(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 $=IW(this._prevFrame,MW.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
238
|
+
`).length-1;this.output.write(I0.move(-999,$*-1))}render(){let $=IW(this._render(this)??"",MW.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(I0.hide);else{let w=nz(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(I0.move(0,A)),this.output.write(lY.lines(1));let J=$.split(`
|
|
239
|
+
`);this.output.write(J[A]),this._prevFrame=$,this.output.write(I0.move(0,J.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(I0.move(0,A)),this.output.write(lY.down());let Y=$.split(`
|
|
240
|
+
`).slice(A);this.output.write(Y.join(`
|
|
241
|
+
`)),this._prevFrame=$;return}this.output.write(lY.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function rz($,w){if($===void 0)return 0;if(w.length===0)return 0;let J=w.findIndex((Y)=>Y.value===$);return J!==-1?J:0}function az($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function sz($,w){if(!w)return;if($)return w;return w[0]}class oz extends oY{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#J;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return zA.inverse(zA.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`${$}${zA.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.#J=$.filter??az;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 J of A){let Y=w.findIndex((U)=>U.value===J);if(Y!==-1)this.toggleSelected(J),this.#$=Y}this.focusedValue=this.options[this.#$]?.value,this.on("key",(J,Y)=>this.#Y(J,Y)),this.on("userInput",(J)=>this.#U(J))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#Y($,w){let A=w.name==="up",J=w.name==="down",Y=w.name==="return";if(A||J){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(Y)this.value=sz(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=[$]}#U($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#J($,A));else this.filteredOptions=[...w];if(this.#$=rz(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 ez extends oY{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((J)=>A.includes(J.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((J)=>A.findIndex((Y)=>Y.value===J)===-1);else this.value=[...this.value,...A.map((J)=>J.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,J])=>[{value:A,group:!0,label:A},...J.map((Y)=>({...Y,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 J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)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 J=this.options[this.cursor]?.group===!0;if(!this.#$&&J)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var $f=Bz();var t=($,w)=>$f?$:w,cq=t("◆","*"),vq=t("■","x"),mq=t("▲","x"),nq=t("◇","o"),dq=t("┌","T"),wf=t("│","|"),gq=t("└","—"),lq=t("●",">"),pq=t("○"," "),tq=t("◻","[•]"),rq=t("◼","[+]"),aq=t("◻","[ ]"),sq=t("▪","•"),oq=t("─","-"),eq=t("╮","+"),$K=t("├","+"),wK=t("╯","+"),AK=t("●","•"),JK=t("◆","*"),YK=t("▲","!"),UK=t("■","x");var ZK={light:t("─","-"),heavy:t("━","="),block:t("█","#")};function Af(){return`${zA.gray(wf)} `}var WK=Af();cU();import{homedir as vU}from"node:os";import{join as mU,resolve as ah}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",f2={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:mU(vU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:mU(vU(),".stacks","ssl","stacks.localhost.crt"),keyPath:mU(vU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var vw=f2;o0();RY();NY();cZ();t1();$A();h1();U$();import{spawn as C9}from"node:child_process";import*as K0 from"node:fs/promises";import{homedir as AW}from"node:os";import*as q0 from"node:path";import*as x from"node:process";var g6=5000;function Z0(){return q0.join(AW(),".stacks","rpx")}function jw($=Z0()){return q0.join($,"daemon.pid")}async function Ew($=Z0()){try{let w=await K0.readFile(jw($),"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 DY($=Z0()){let w=await Ew($);return w!==null&&m$(w)}async function l6($=Z0()){await K0.mkdir($,{recursive:!0});let w=jw($);while(!0){try{let J=await K0.open(w,"wx");try{await J.write(`${x.pid}
|
|
242
|
+
`)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=await Ew($);if(A!==null&&m$(A))throw Error(`rpx daemon already running (pid=${A})`);await K0.unlink(w).catch(()=>{})}}async function JA($=Z0()){await K0.unlink(jw($)).catch(()=>{})}function p6($){let w=$.cleanUrls??!1;if($.static)return{static:p1($.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 t6($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function r6($,w){let A=await hw(w,$.verbose),J=[...new Set(A.map((j)=>j.to))],Y=t6(J),U=[...new Set([Y,...J,"rpx.localhost"])],Z=q0.join(AW(),".stacks","ssl"),B=q0.join(Z,"rpx.localhost.crt"),W={https:typeof $.https==="object"?{...$.https,certPath:B,keyPath:q0.join(Z,"rpx.localhost.key"),commonName:Y}:{certPath:B,keyPath:q0.join(Z,"rpx.localhost.key"),caCertPath:q0.join(Z,"rpx.localhost.ca.crt"),commonName:Y},verbose:$.verbose,regenerateUntrustedCerts:!0,...U.length>1?{proxies:U.map((j)=>({from:"localhost:1",to:j}))}:{to:Y,from:"localhost:1"}},E=await g0(W);if(!E)G("daemon","no usable cert on disk, generating one",$.verbose),await K1(W),E=await g0(W);if(!E)throw Error("failed to bootstrap TLS for rpx daemon");return E}async function a6($,w,A,J){let Y=x.env.SUDO_PASSWORD,U=x.env.HOME??AW(),Z=[x.execPath,...x.argv.slice(1)],B=[`HOME=${U}`,`PATH=${x.env.PATH??""}`];if(J)B.push("RPX_VERBOSE=1");let W=Y?["-S","-p","","env",...B,...Z]:["-n","env",...B,...Z];G("daemon",`elevating daemon via sudo for privileged ports ${w}/${A}`,J);let E=C9("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),j=null,F=null;if(E.once("error",(H)=>{j=H}),E.once("exit",(H)=>{F=H??0}),Y&&E.stdin)E.stdin.write(`${Y}
|
|
243
|
+
`),E.stdin.end();E.unref();let f=jw($),z=Date.now()+15000;while(Date.now()<z){if(j)throw j;let H=await Ew($);if(H!==null&&m$(H)){if(J)R.success(`rpx daemon elevated to root (pid=${H}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:f,done:Promise.resolve(),stop:async()=>{try{x.kill(H,"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 L9($={}){let w=$.verbose??!1,A=$.rpxDir??Z0(),J=$.registryDir??q0.join(A,"registry.d"),Y=$.httpsPort??443,U=$.httpPort??80,Z=$.hostname??"0.0.0.0",B=$.gcIntervalMs??g6,W=Y>0&&Y<1024||U>0&&U<1024,E=typeof x.getuid==="function"&&x.getuid()===0;if(x.platform!=="win32"&&W&&!E)return a6(A,Y,U,w);let j=await l6(A),F=new Map,f=(y)=>s1(F,y);function z(y){let X$=new Map;for(let M0 of y)X$.set(M0.to,p6(M0));F=X$,G("daemon",`routing table now covers ${X$.size} host(s): ${Array.from(X$.keys()).join(", ")||"<empty>"}`,w)}await LY(J,w).catch((y)=>{G("daemon",`initial gc failed: ${y}`,w)});let H=await hw(J,w);z(H),await Ww({rpxDir:A,verbose:w}).catch((y)=>{G("daemon",`DNS reconcile on start failed: ${y}`,w)}),await AA(H,{rpxDir:A,verbose:w,ownerPid:x.pid}).catch((y)=>{G("daemon",`DNS setup on start failed: ${y}`,w)});let T=[];if($.productionCerts){if(T=await uZ($.productionCerts,w),w&&T.length>0)R.info(`SNI: serving ${T.length} real cert(s): ${T.map((y)=>y.serverName).join(", ")}`)}let q=r1(f,w),K=a1(w),h;if(T.length>0)h=T.map((y)=>({serverName:y.serverName,cert:y.cert,key:y.key}));else{let y=await r6($,J);h={key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1}}let I=Bun.serve({port:Y,hostname:Z,tls:h,fetch(y,X$){return q(y,X$)},websocket:K,error(y){return G("daemon",`https server error: ${y}`,w),new Response(`Server Error: ${y.message}`,{status:500})}}),N=null;if(U>0)N=Bun.serve({port:U,hostname:Z,fetch(y){let X$=new URL(y.url),M0=(y.headers.get("host")??X$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${M0}${X$.pathname}${X$.search}`}})}});if(w)R.success(`rpx daemon listening on https://${Z}:${Y}${N?` (http→https on :${U})`:""}`),R.info(`pid file: ${j}`),R.info(`registry: ${J}`);let M=dZ((y)=>{z(y),AA(y,{rpxDir:A,verbose:w,ownerPid:x.pid}).catch((X$)=>{G("daemon",`DNS sync on registry change failed: ${X$}`,w)})},{dir:J,verbose:w}),V=setInterval(()=>{LY(J,w).then((y)=>{if(y>0)G("daemon",`gc reaped ${y} stale entries`,w)}).catch((y)=>{G("daemon",`periodic gc failed: ${y}`,w)})},B);if(typeof V.unref==="function")V.unref();let g$=!1,B0,N0=new Promise((y)=>{B0=y});async function Fw(){if(g$)return N0;if(g$=!0,clearInterval(V),M.close(),I.stop(!1),N?.stop(!1),await Nw({rpxDir:A,verbose:w}).catch((y)=>{G("daemon",`DNS teardown failed: ${y}`,w)}),await JA(A),w)R.info("rpx daemon stopped");return B0(),N0}let M1=(y)=>{G("daemon",`received ${y}, shutting down`,w),Fw().catch(()=>{})};return x.once("SIGINT",M1),x.once("SIGTERM",M1),{stop:Fw,done:N0,httpsPort:typeof I.port==="number"?I.port:Y,httpPort:N&&typeof N.port==="number"?N.port:U,pidPath:j}}function s6(){let $=x.execPath,w=q0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&x.argv[1])return[$,x.argv[1],"daemon:start"];return[$,"daemon:start"]}async function y9($={}){let w=$.rpxDir??Z0(),A=$.verbose??!1;await Ww({rpxDir:w,verbose:A}).catch((j)=>{G("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,A)});let J=await Ew(w);if(J!==null&&m$(J))return G("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)G("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await JA(w);await K0.mkdir(w,{recursive:!0});let Y=$.spawnCommand??s6();if(Y.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");G("daemon",`spawning daemon: ${Y.join(" ")}`,A);let U=C9(Y[0],Y.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??x.cwd(),env:$.spawnEnv?{...x.env,...$.spawnEnv}:x.env});U.unref();let Z=null;U.once("error",(j)=>{Z=j});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,E=Date.now()+B;while(Date.now()<E){if(Z)throw Z;let j=await Ew(w);if(j!==null&&m$(j))return G("daemon",`daemon registered with pid=${j}`,A),{pid:j,spawned:!0};await new Promise((F)=>setTimeout(F,W))}if(Z)throw Z;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}async function V9($={}){let w=$.rpxDir??Z0(),A=$.verbose??!1,J=$.timeoutMs??5000,Y=$.pollIntervalMs??50,U=$.forceAfterTimeout??!0,Z=await Ew(w);if(Z===null||!m$(Z)){if(Z!==null)await JA(w);return await Ww({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:Z,forced:!1}}try{x.kill(Z,"SIGTERM")}catch(W){if(W.code==="ESRCH")return await JA(w),{stopped:!1,pid:Z,forced:!1};throw W}let B=Date.now()+J;while(Date.now()<B){if(!m$(Z))return G("daemon",`daemon pid=${Z} stopped cleanly`,A),{stopped:!0,pid:Z,forced:!1};await new Promise((W)=>setTimeout(W,Y))}if(!U)throw Error(`rpx daemon (pid=${Z}) did not exit within ${J}ms`);G("daemon",`daemon pid=${Z} did not exit, escalating to SIGKILL`,A);try{x.kill(Z,"SIGKILL")}catch(W){if(W.code!=="ESRCH")throw W}return await JA(w),await Nw({rpxDir:w,verbose:A}).catch((W)=>{G("daemon",`DNS teardown after SIGKILL: ${W}`,A)}),{stopped:!0,pid:Z,forced:!0}}async function S9($={}){let w=$.rpxDir??Z0();if(await DY(w))return;await Ww({rpxDir:w,verbose:$.verbose})}o0();U$();import{spawn as o6}from"node:child_process";import*as Mw from"node:process";class O9{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){G("start",`Process ${$} is already running`,A);return}let[J,...Y]=w.command.split(" "),U=w.cwd||Mw.cwd();G("start",`Starting process ${$}:`,A),G("start",` Command: ${J} ${Y.join(" ")}`,A),G("start",` Working directory: ${U}`,A),G("start",` Environment variables: ${Y0(w.env)}`,A);let Z=o6(J,Y,{cwd:U,env:{...Mw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:U,process:Z,env:w.env}),new Promise((B,W)=>{if(Z.on("error",(E)=>{if(!this.isShuttingDown)G("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),W(E),Mw.emit("SIGINT")}),Z.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)G("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),W(Error(`Process ${$} exited with code ${E}`)),Mw.emit("SIGINT")}),A)Z.stdout?.on("data",(E)=>{G("process",`[${$}] ${E.toString().trim()}`,!0)}),Z.stderr?.on("data",(E)=>{G("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&Z.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else G("start",`Process ${$} started successfully`,A),B()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){G("start",`No process found for ${$}`,w);return}return G("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),G("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){G("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){G("start",`Error stopping process ${$}: ${Y}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){G("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,G("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{R.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 QY=new O9;U$();import*as c$ from"node:fs/promises";import{homedir as e6}from"node:os";import*as JW from"node:path";import*as YW from"node:process";var $q=/^[a-zA-Z0-9._-]+$/;function Iw(){return JW.join(e6(),".stacks","rpx","registry.d")}function N1($){return typeof $==="string"&&$.length>0&&$.length<=128&&$q.test($)}function UW($,w){if(!N1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return JW.join($,`${w}.json`)}function X9($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,J=typeof w.from==="string"&&w.from.length>0,Y=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string";return typeof w.id==="string"&&N1(w.id)&&(J||Y)&&typeof w.to==="string"&&w.to.length>0&&A&&typeof w.createdAt==="string"}async function wq($){await c$.mkdir($,{recursive:!0})}async function _9($,w=Iw(),A){if(!X9($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await wq(w);let J=UW(w,$.id),Y=`${J}.tmp.${YW.pid}.${Date.now()}`,U=JSON.stringify($,null,2);try{await c$.writeFile(Y,U,{encoding:"utf8",mode:420}),await c$.rename(Y,J),G("registry",`wrote entry ${$.id} → ${J}`,A)}catch(Z){throw await c$.unlink(Y).catch(()=>{}),Z}}async function D9($,w=Iw(),A){let J=UW(w,$);try{await c$.unlink(J),G("registry",`removed entry ${$}`,A)}catch(Y){if(Y.code!=="ENOENT")throw Y}}async function ZW($,w=Iw(),A){let J=UW(w,$);try{let Y=await c$.readFile(J,"utf8"),U=JSON.parse(Y);if(!X9(U))return G("registry",`entry ${$} failed validation, removing`,A),await c$.unlink(J).catch(()=>{}),null;return U}catch(Y){if(Y.code==="ENOENT")return null;if(Y instanceof SyntaxError)return G("registry",`entry ${$} has invalid JSON, removing`,A),await c$.unlink(J).catch(()=>{}),null;throw Y}}async function Q9($=Iw(),w){let A;try{A=await c$.readdir($)}catch(Y){if(Y.code==="ENOENT")return[];throw Y}let J=[];for(let Y of A){if(!Y.endsWith(".json"))continue;let U=Y.slice(0,-5);if(!N1(U))continue;let Z=await ZW(U,$,w);if(Z)J.push(Z)}return J}o0();import{execSync as Wq}from"node:child_process";import*as Vw from"node:http";import*as v9 from"node:http2";import*as m9 from"node:net";import*as e from"node:process";var kY=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,h0={bold:kY(1,22),dim:kY(2,22),green:kY(32,39),cyan:kY(36,39)};d8();gZ();o0();$A();U$();import*as k9 from"node:fs";import*as x9 from"node:path";import*as R0 from"node:process";function Aq($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function WW($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,Y=$.proxies.map((f)=>{let z=f.id??Aq(f.to);if(!e1(z))throw Error(`invalid registry id "${z}" derived from to="${f.to}"`);if(J.has(z))throw Error(`duplicate registry id "${z}" — set an explicit \`id\` on one of the proxies`);return J.add(z),{...f,id:z}}),U=new Date().toISOString();for(let f of Y)await B9({id:f.id,from:f.from,to:f.to,pid:$.persistent?void 0:R0.pid,cwd:R0.cwd(),createdAt:U,cleanUrls:f.cleanUrls,changeOrigin:f.changeOrigin,pathRewrites:f.pathRewrites,static:f.static},A,w);let Z=await F9({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let f of Y){let z=f.static?`static ${typeof f.static==="string"?f.static:f.static.dir}`:f.from;R.success(`https://${f.to} → ${z}`)}if(R.info(`(via rpx daemon pid=${Z.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let B=!1,W=A??Zw(),E=Y.map((f)=>f.id),j=async()=>{if(B)return;B=!0;for(let f of E)await nZ(f,A,w).catch((z)=>{G("runner",`removeEntry(${f}) failed: ${z}`,w)})},F=(f)=>{G("runner",`received ${f}, unregistering ${E.length} entries`,w),j().finally(()=>R0.exit(0))};R0.once("SIGINT",F),R0.once("SIGTERM",F),R0.once("exit",()=>{if(B)return;for(let f of E)try{k9.unlinkSync(x9.join(W,`${f}.json`))}catch{}}),await new Promise(()=>{})}U$();import{exec as Jq}from"node:child_process";import Cw from"node:fs";import b9 from"node:os";import EW from"node:path";import*as YA from"node:process";import{promisify as Yq}from"node:util";var xY=Yq(Jq);function P9($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var W0=YA.platform==="win32"?EW.join(YA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",BW=!1;async function PY($){if(YA.platform==="win32")throw Error("Administrator privileges required on Windows");let w=qw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:J}=await xY(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return BW=!0,J}if(BW)try{let{stdout:J}=await xY(`sudo -n sh -c '${A}'`);return J}catch(J){G("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:J}=await xY(`sudo -n sh -c '${A}'`);return BW=!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 UA($,w){let A=$.filter((Y)=>!P9(Y)),J=$.filter((Y)=>P9(Y));if(J.length>0)G("hosts",`Skipping /etc/hosts for loopback dev names: ${J.join(", ")}`,w);if(A.length===0)return;G("hosts",`Adding hosts: ${A.join(", ")}`,w),G("hosts",`Using hosts file at: ${W0}`,w);try{let Y;try{Y=await Cw.promises.readFile(W0,"utf-8")}catch{G("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{Y=await PY(`cat "${W0}"`)}catch(W){throw console.log(" Could not read hosts file — skipping hosts setup"),G("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let U=A.filter((W)=>{let E=`127.0.0.1 ${W}`,j=`::1 ${W}`;return!Y.includes(E)&&!Y.includes(j)});if(U.length===0){G("hosts","All hosts already exist in hosts file",w);return}let Z=U.map((W)=>`
|
|
244
244
|
# Added by rpx
|
|
245
|
-
127.0.0.1 ${
|
|
246
|
-
::1 ${
|
|
247
|
-
`),
|
|
248
|
-
`),
|
|
245
|
+
127.0.0.1 ${W}
|
|
246
|
+
::1 ${W}`).join(`
|
|
247
|
+
`),B=EW.join(b9.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Cw.promises.writeFile(B,Y+Z,"utf8"),await PY(`cat "${B}" | tee "${W0}" > /dev/null`),console.log(` Hosts updated: ${U.join(", ")}`)}catch(W){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((E)=>{console.log(` 127.0.0.1 ${E}`),console.log(` ::1 ${E}`)}),console.log(` Or run: sudo nano ${W0}`)}finally{try{await Cw.promises.unlink(B)}catch{}}}catch(Y){G("hosts",`Failed to manage hosts file: ${Y.message}`,w)}}async function i9($,w){G("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await Cw.promises.readFile(W0,"utf-8")}catch{G("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await PY(`cat "${W0}"`)}catch(W){throw G("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let J=A.split(`
|
|
248
|
+
`),Y=!1,U=J.filter((W)=>{if($.some((j)=>W.includes(` ${j}`)&&(W.includes("127.0.0.1")||W.includes("::1"))))return Y=!0,!1;if(W.trim()==="# Added by rpx")return Y=!0,!1;return!0});if(!Y){G("hosts","No matching hosts found to remove",w);return}while(U[U.length-1]?.trim()==="")U.pop();let Z=`${U.join(`
|
|
249
249
|
`)}
|
|
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();
|
|
250
|
+
`,B=EW.join(b9.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Cw.promises.writeFile(B,Z,"utf8"),await PY(`cat "${B}" | tee "${W0}" > /dev/null`),G("hosts","Hosts removed successfully",w)}catch(W){G("hosts","Could not clean up hosts file automatically",w)}finally{try{await Cw.promises.unlink(B)}catch(W){G("hosts",`Failed to remove temporary file: ${W}`,w)}}}catch(A){G("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function ZA($,w){G("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Cw.promises.readFile(W0,"utf-8")}catch(J){G("hosts",`Error reading hosts file: ${J}`,w);try{let Y=qw(),U;if(Y)U=`echo '${Y}' | sudo -S cat "${W0}" 2>/dev/null`;else U=`sudo -n cat "${W0}" 2>/dev/null || cat "${W0}" 2>/dev/null || echo ""`;let{stdout:Z}=await xY(U);A=Z}catch(Y){return G("hosts",`Cannot read hosts file, assuming entries don't exist: ${Y}`,w),$.map(()=>!1)}}return $.map((J)=>{let Y=`127.0.0.1 ${J}`,U=`::1 ${J}`;return A.includes(Y)||A.includes(U)})}RY();U$();import*as bY from"node:net";function Lw($,w,A){return G("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let Y=bY.createServer(),U=setTimeout(()=>{G("port",`Checking port ${$} timed out, assuming it's in use`,A),Y.close(),J(!0)},3000);Y.once("error",(Z)=>{if(clearTimeout(U),Z.code==="EADDRINUSE")G("port",`Port ${$} is in use`,A),J(!0);else G("port",`Error checking port ${$}: ${Z.message}`,A),J(!0)}),Y.once("listening",()=>{clearTimeout(U),G("port",`Port ${$} is available`,A),Y.close(),J(!1)});try{Y.listen($,w)}catch(Z){clearTimeout(U),G("port",`Exception checking port ${$}: ${Z}`,A),J(!0)}})}async function Uq($,w,A,J=50){G("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let Y=$,U=0;while(U<J){if(U++,!await Lw(Y,w,A))return G("port",`Found available port: ${Y} after ${U} attempts`,A),Y;G("port",`Port ${Y} is in use, trying ${Y+1} (attempt ${U}/${J})`,A),Y++}throw Error(`Unable to find available port after ${J} attempts starting from ${$}`)}function u9($,w,A=5000,J){return G("port",`Testing connection to ${w}:${$}`,J),new Promise((Y)=>{let U=bY.connect({host:w,port:$,timeout:A});U.once("connect",()=>{G("port",`Successfully connected to ${w}:${$}`,J),U.end(),Y(!0)}),U.once("timeout",()=>{G("port",`Connection to ${w}:${$} timed out`,J),U.destroy(),Y(!1)}),U.once("error",(Z)=>{G("port",`Failed to connect to ${w}:${$}: ${Z.message}`,J),U.destroy(),Y(!1)})})}class iY{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 Lw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await u9($,this.hostname,3000,this.verbose))return G("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await Uq($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await u9(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){G("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var iC=new iY;o0();U$();import{spawn as Zq}from"node:child_process";import*as yw from"node:process";class uY{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){G("start",`Process ${$} is already running`,A);return}let[J,...Y]=w.command.split(" "),U=w.cwd||yw.cwd();G("start",`Starting process ${$}:`,A),G("start",` Command: ${J} ${Y.join(" ")}`,A),G("start",` Working directory: ${U}`,A),G("start",` Environment variables: ${Y0(w.env)}`,A);let Z=Zq(J,Y,{cwd:U,env:{...yw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:U,process:Z,env:w.env}),new Promise((B,W)=>{if(Z.on("error",(E)=>{if(!this.isShuttingDown)G("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),W(E),yw.emit("SIGINT")}),Z.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)G("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),W(Error(`Process ${$} exited with code ${E}`)),yw.emit("SIGINT")}),A)Z.stdout?.on("data",(E)=>{G("process",`[${$}] ${E.toString().trim()}`,!0)}),Z.stderr?.on("data",(E)=>{G("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&Z.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else G("start",`Process ${$} started successfully`,A),B()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){G("start",`No process found for ${$}`,w);return}return G("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),G("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){G("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(Y){}}},3000)}catch(Y){G("start",`Error stopping process ${$}: ${Y}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){G("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,G("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((J)=>{R.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 nC=new uY;NY();t1();U$();var vY=new uY,Bq="0.12.0",Eq=new iY("0.0.0.0"),WA=new Set,jW=!1,cY=null,FW=null;async function mY($){if(jW)return G("cleanup","Cleanup already in progress, skipping",$?.verbose),FW||Promise.resolve();jW=!0,G("cleanup","Starting cleanup process",$?.verbose),FW=new Promise((w)=>{cY=w});try{await vY.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],A=Array.from(WA).map((J)=>new Promise((Y)=>{J.close(()=>{G("cleanup","Server closed successfully",$?.verbose),Y()})}));if(w.push(...A),$?.hosts&&$.domains?.length){G("cleanup","Cleaning up hosts file entries",$?.verbose),G("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((Y)=>{if(Y==="test.local")return!0;return Y!=="localhost"&&!Y.startsWith("localhost.")&&Y!=="127.0.0.1"});if(G("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)R.info("Cleaning up hosts file entries..."),w.push(i9(J,$?.verbose).then(()=>{G("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((Y)=>{G("cleanup",`Failed to remove hosts entries: ${Y}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,Y)}))}if($?.certs&&$.domains?.length){G("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let J=$.domains.map(async(Y)=>{try{await J9(Y,$?.verbose),G("cleanup",`Removed certificates for ${Y}`,$?.verbose)}catch(U){G("cleanup",`Failed to remove certificates for ${Y}: ${U}`,$?.verbose),R.warn(`Failed to clean up certificates for ${Y}:`,U)}});w.push(...J)}await Promise.allSettled(w),G("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){G("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(cY)cY();cY=null,jW=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(e.env.NODE_ENV!=="test"&&e.env.BUN_ENV!=="test"&&!w)e.exit(0)}return FW}var zW=!1;function fW($){if(zW){G("signal",`Received second ${$} signal, forcing exit`,!0),e.exit(1);return}zW=!0,G("signal",`Received ${$} signal, initiating cleanup`,!0),mY().catch((w)=>{G("signal",`Cleanup failed after ${$}: ${w}`,!0),e.exit(1)}).finally(()=>{zW=!1})}e.once("SIGINT",()=>fW("SIGINT"));e.once("SIGTERM",()=>fW("SIGTERM"));e.on("uncaughtException",($)=>{G("process",`Uncaught exception: ${$}`,!0),R.error("Uncaught exception:",$),fW("uncaughtException")});async function BA($,w,A,J=5){G("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let Y=15000,U=Date.now();if(e.env.RPX_BYPASS_CONNECTION_TEST==="true"){G("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let Z=()=>new Promise((B,W)=>{let E=m9.connect({host:$,port:w,timeout:3000});E.once("connect",()=>{G("connection",`Successfully connected to ${$}:${w}`,A),E.end(),B()}),E.once("timeout",()=>{G("connection",`Connection to ${$}:${w} timed out`,A),E.destroy(),W(Error("Connection timed out"))}),E.once("error",(j)=>{G("connection",`Failed to connect to ${$}:${w}: ${j}`,A),E.destroy(),W(j)})});try{await Z()}catch(B){if(Date.now()-U>Y){G("connection",`Connection test timed out after ${Y}ms, but continuing anyway`,A),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(B.code==="ECONNREFUSED"&&J>0)return G("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),BA($,w,A,J-1);if(J>0)try{G("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((E,j)=>{let F=Vw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(f)=>{G("connection",`Received HTTP response with status: ${f.statusCode}`,A),E()});F.on("error",(f)=>j(f)),F.on("timeout",()=>{F.destroy(),j(Error("HTTP request timed out"))}),F.end()}),G("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(E){return G("connection",`HTTP request to ${$}:${w} failed: ${E}`,A),G("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((j)=>setTimeout(j,2000)),BA($,w,A,J-1)}let W=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${B.message}`;G("connection",`${W}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),R.warn(W),R.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function n9($){G("server",`Starting server with options: ${Y0($)}`,$.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),Y=[A.hostname];if(GW($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){G("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await ZA(Y,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await UA(Y,$.verbose)}catch(B){if(R.error("Failed to add hosts entry:",B.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),e.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else G("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(Z){R.error("Failed to check hosts file:",Z.message)}}try{await BA(w.hostname,J,$.verbose)}catch(Z){G("server",`Connection test failed: ${Z}`,$.verbose),R.error(Z.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=l1({...$,to:A.hostname});if(U=await g0({...$,to:A.hostname,https:$.https}),!U){if(G("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await K1({...$,from:w.toString(),to:A.hostname,https:$.https}),U=await g0({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(Z){throw G("server",`SSL setup failed: ${Z}`,$.verbose),Z}G("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await Fq({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:U})}async function jq($,w,A,J,Y,U,Z,B,W,E,j){G("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${E}`,W);function F(T){let q={};for(let[K,h]of Object.entries(T))if(!K.startsWith(":"))q[K]=h;return q}let f=(T,q)=>{G("request",`Incoming request: ${T.method} ${T.url}`,W);let K=T.url||"/",h=T.method||"GET";if(T instanceof v9.Http2ServerRequest){let V=T.headers;h=V[":method"]||h,K=V[":path"]||K}if(E){if(!K.match(/\.[a-z0-9]+$/i))if(K.endsWith("/"))K=`${K}index.html`;else K=`${K}.html`}let I=F(T.headers);if(j)I.host=`${U.hostname}:${A}`,G("request",`Changed origin: setting host header to ${I.host}`,W);let N={hostname:U.hostname,port:A,path:K,method:h,headers:I};G("request",`Proxy request options: ${Y0(N)}`,W);let M=Vw.request(N,(V)=>{if(G("response",`Proxy response received with status ${V.statusCode}`,W),E&&V.statusCode===404){let B0=[];if(K.endsWith(".html"))B0.push(K.slice(0,-5));else if(!K.match(/\.[a-z0-9]+$/i))B0.push(`${K}.html`);if(!K.endsWith("/"))B0.push(`${K}/index.html`);if(B0.length>0){G("cleanUrls",`Trying alternative paths: ${B0.join(", ")}`,W);let N0=(Fw)=>{if(Fw.length===0){q.writeHead(V.statusCode||404,V.headers),V.pipe(q);return}let M1=Fw[0],y={...N,path:M1},X$=Vw.request(y,(M0)=>{if(M0.statusCode===200)G("cleanUrls",`Found matching path: ${M1}`,W),q.writeHead(M0.statusCode,M0.headers),M0.pipe(q);else N0(Fw.slice(1))});X$.on("error",()=>N0(Fw.slice(1))),X$.end()};N0(B0);return}}let g$={...V.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};q.writeHead(V.statusCode||500,g$),V.pipe(q)});M.on("error",(V)=>{G("request",`Proxy request failed: ${V}`,W),R.error("Proxy request failed:",V),q.writeHead(502),q.end(`Proxy Error: ${V.message}`)}),T.pipe(M)};if(G("server",`Creating server with SSL config: ${!!Z}`,W),Z)return new Promise((T,q)=>{try{let K=Bun.serve({port:J,hostname:Y,tls:{key:Z.key,cert:Z.cert,ca:Z.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(h){let I=new URL(h.url);G("request",`Bun.serve received: ${h.method} ${I.pathname}`,W);let N=`http://${U.host}`,M=new URL(I.pathname+I.search,N);try{let V=new Headers(h.headers);if(V.set("host",U.host),j)V.set("origin",N);V.set("x-forwarded-for","127.0.0.1"),V.set("x-forwarded-proto","https"),V.set("x-forwarded-host",w);let g$=await fetch(M.toString(),{method:h.method,headers:V,body:h.body,redirect:"manual"}),B0=new Headers(g$.headers);if(E&&I.pathname.endsWith(".html")){let N0=I.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:N0}})}return new Response(g$.body,{status:g$.status,statusText:g$.statusText,headers:B0})}catch(V){return G("request",`Proxy error: ${V}`,W),new Response(`Proxy Error: ${V}`,{status:502})}},error(h){return G("server",`Bun.serve error: ${h}`,W),new Response(`Server Error: ${h.message}`,{status:500})}});WA.add(K),c9({from:$,to:w,vitePluginUsage:B,listenPort:J,ssl:!0,cleanUrls:E,verbose:W}),T()}catch(K){q(K)}});let z=Vw.createServer(f);function H(T){return WA.add(T),new Promise((q,K)=>{T.listen(J,Y,()=>{G("server",`Server listening on port ${J}`,W),c9({from:$,to:w,vitePluginUsage:B,listenPort:J,ssl:!!Z,cleanUrls:E,verbose:W}),q()}),T.on("error",(h)=>{G("server",`Server error: ${h}`,W),K(h)})})}return H(z)}async function Fq($){G("setup",`Setting up reverse proxy: ${Y0($)}`,$.verbose);let{from:w,to:A,fromPort:J,sourceUrl:Y,ssl:U,verbose:Z,cleanup:B,vitePluginUsage:W,changeOrigin:E,cleanUrls:j}=$,F=80,f=443,z="0.0.0.0",H=$.portManager||Eq,T=GW($);try{if(T&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await ZA([A],Z))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await UA([A],Z),R.success(`Added ${A} to your hosts file.`)}catch(N){R.error(`Failed to add ${A} to your hosts file: ${N}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(T&&e.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await ZA([A],Z))[0]){G("hosts",`${A} not found in hosts file, adding...`,Z);try{await UA([A],Z)}catch(N){G("hosts",`Failed to add ${A} to hosts file: ${N}`,Z)}}}if(U&&!H.usedPorts.has(F)){if(!await Lw(F,z,Z))G("setup","Starting HTTP redirect server",Z),d9(Z),H.usedPorts.add(F);else if(G("setup","Port 80 is in use, skipping HTTP redirect",Z),Z)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let q=U?f:F,K=await Lw(q,z,Z),h;if(K){if(G("setup",`Port ${q} is already in use`,Z),Z)R.warn(`Port ${q} is already in use. This may be another instance of rpx or another service.`);if(q===443){if(h=await H.getNextAvailablePort(3443,!0),G("setup",`Using port ${h} instead of ${q}`,Z),Z)R.info(`Using port ${h} instead. Access your site at https://${A}:${h}`)}else if(h=await H.getNextAvailablePort(q+1000,!0),G("setup",`Using port ${h} instead of ${q}`,Z),Z)R.info(`Using port ${h} instead. Access your site at http://${A}:${h}`)}else h=q,H.usedPorts.add(h),G("setup",`Using standard ${q===443?"HTTPS":"HTTP"} port ${q} for ${A}`,Z);await jq(w,A,J,h,z,Y,U,W,Z,j,E)}catch(q){G("setup",`Setup failed: ${q}`,Z),R.error(`Failed to setup reverse proxy: ${q.message}`),mY({domains:[A],hosts:typeof B==="boolean"?B:B?.hosts,certs:typeof B==="boolean"?B:B?.certs,verbose:Z,vitePluginUsage:W})}}function d9($){G("redirect","Starting HTTP redirect server",$);let w=Vw.createServer((A,J)=>{let Y=A.headers.host||"";G("redirect",`Redirecting request from ${Y}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${Y}${A.url}`}),J.end()}).listen(80);WA.add(w),G("redirect","HTTP redirect server started",$)}function g9($){let w={...n8,...$};if(G("proxy",`Starting proxy with options: ${Y0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}WW({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),e.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",Y=e.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),U=["dev","app","page","new","day","foo"],Z=["test","localhost","local","example","invalid"];if(Y&&U.includes(J)&&w?.verbose)R.warn(`The .${J} TLD may not work reliably for local development`),R.info(` Google owns .${J} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(Y)Promise.resolve().then(() => (h1(),_Y)).then(({setupDevelopmentDns:W})=>{W({domains:[A],verbose:w.verbose}).then((E)=>{if(E)Promise.resolve().then(()=>{if(w.verbose)if(Z.includes(J))R.success(`DNS server started for .${J} domains`);else R.success(`DNS server started for .${J} domains (hosts file entry also added)`)});else G("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((W)=>{G("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:l1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};G("proxy",`Server options: ${Y0(B)}`,w.verbose),n9(B).catch((W)=>{G("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),mY({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 zq($){return $?.verbose||!1}function GW($){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 l9($){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=zq(w),J=GW(w);if(G("config",`Starting with config: ${Y0(w,2)}`,A),G("config",`Is multi-proxy? ${"proxies"in w}`,A),G("config",`Hosts management enabled? ${J}`,A),w.viaDaemon){let T="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((q)=>({id:q.id,from:q.from,to:q.to,cleanUrls:q.cleanUrls??w.cleanUrls,changeOrigin:q.changeOrigin??w.changeOrigin,pathRewrites:q.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await WW({proxies:T,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){G("servers",`Found ${w.proxies.length} proxies in config`,A);for(let H of w.proxies)if(H.start){let T=`${H.from}-${H.to}`;try{G("watch",`Starting command for ${T} with command: ${H.start.command}`,A),R.info(`Starting command for ${T}...`),await vY.startProcess(T,H.start,A);let q=new URL(H.from.startsWith("http")?H.from:`http://${H.from}`),K=q.hostname||"localhost",h=Number(q.port)||80;try{await BA(K,h,A),G("watch",`Dev server is ready at ${K}:${h}`,A)}catch(I){G("watch",`Connection check failed, but continuing with proxy setup: ${I}`,A),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(q){throw G("watch",`Failed to start command for ${T}: ${q}`,A),Error(`Failed to start command for ${T}: ${q}`)}}else G("watch",`No start command for proxy ${H.from} -> ${H.to}`,A)}else if("start"in w&&w.start){G("watch","Found start command in single proxy config",A);let H=`${w.from}-${w.to}`;try{if(w.start)G("watch",`Starting command: ${w.start.command}`,A),await vY.startProcess(H,w.start,A);let T=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),q=T.hostname||"localhost",K=Number(T.port)||80;try{await BA(q,K,A),G("watch",`Dev server is ready at ${q}:${K}`,A)}catch(h){G("watch",`Connection check failed, but continuing with proxy setup: ${h}`,A),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw G("watch",`Failed to run start command: ${T}`,A),Error(`Failed to run start command: ${T}`)}}else G("watch","No start command found in config",A);let Y="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(e.platform!=="win32"&&(w.https||J)){if(!qw())try{G("sudo","Pre-acquiring sudo credentials for privileged operations",A),Wq("sudo -v",{stdio:"inherit"})}catch{G("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let H=await g0(w);if(!H){if(G("ssl",`No valid or trusted certificates found for ${Y}, generating new ones`,w.verbose),await K1(w),H=await g0(w),!H)throw Error(`Failed to load SSL certificates after generation for ${Y}`)}else G("ssl",`Using existing and trusted certificates for ${Y}`,w.verbose);w._cachedSSLConfig=H}let U="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}],Z=U.map((H)=>H.to||"rpx.localhost"),B=w._cachedSSLConfig,W=Z.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),E=["dev","app","page","new","day","foo"],j=["test","localhost","local","example","invalid"],F=[...new Set(W.map((H)=>H.split(".").pop()?.toLowerCase()))],f=F.filter((H)=>!!H&&E.includes(H));if(f.length>0&&A)R.warn(`The following TLDs may not work reliably for local development: ${f.map((H)=>`.${H}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(J&&e.platform==="darwin"&&W.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (h1(),_Y));if(await H({domains:W,verbose:A})){if(A)if(F.every((K)=>!!K&&j.includes(K)))R.success(`DNS server started for ${F.map((K)=>`.${K}`).join(", ")} domains`);else R.success(`DNS server started for ${F.map((K)=>`.${K}`).join(", ")} domains (hosts file entries also added)`)}else G("dns","Could not start DNS server - custom domains may not resolve",A)}let z=async()=>{G("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (h1(),_Y));await H({verbose:w.verbose})}catch(H){G("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await vY.stopAll(w.verbose)}catch(H){G("cleanup",`Error stopping processes: ${H}`,w.verbose)}await mY({domains:Z,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",(H)=>{G("process",`Uncaught exception: ${H}`,!0),console.error("Uncaught exception:",H),z()}),B&&U.length>1){G("proxies",`Creating shared HTTPS server for ${U.length} domains`,A);let H=new Map;for(let N of U){let M=N.to||"rpx.localhost",V=N.cleanUrls||!1;if(N.static)H.set(M,{static:p1(N.static,V),cleanUrls:V}),G("proxies",`Route: ${M} → static ${typeof N.static==="string"?N.static:N.static.dir}`,A);else{let g$=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`);H.set(M,{sourceHost:g$.host,cleanUrls:V,changeOrigin:N.changeOrigin||!1,pathRewrites:N.pathRewrites}),G("proxies",`Route: ${M} → ${g$.host}`,A)}if(J&&!MY(M)&&!M.includes("localhost")&&!M.includes("127.0.0.1"))try{if(!(await ZA([M],A))[0])await UA([M],A)}catch{G("hosts",`Could not add hosts entry for ${M}`,A)}}if(!await Lw(80,"0.0.0.0",A))d9(A);let q=443;if(await Lw(q,"0.0.0.0",A)){if(G("proxies",`Port ${q} is already in use, cannot start shared proxy`,A),A)R.warn(`Port ${q} is in use. Shared HTTPS proxy cannot start.`);return}let h=r1((N)=>s1(H,N),A),I=a1(A);try{let N=Bun.serve({port:q,hostname:"0.0.0.0",tls:{key:B.key,cert:B.cert,ca:B.ca,requestCert:!1,rejectUnauthorized:!1},fetch(M,V){return h(M,V)},websocket:I,error(M){return G("server",`Shared proxy server error: ${M}`,A),new Response(`Server Error: ${M.message}`,{status:500})}});WA.add(N),G("proxies",`Shared HTTPS proxy listening on port ${q} for ${H.size} domains`,A)}catch(N){G("proxies",`Failed to start shared proxy: ${N}`,A),console.error("Failed to start shared HTTPS proxy:",N),z()}}else for(let H of U)try{let T=H.to||"rpx.localhost";G("proxy",`Starting proxy for ${T} with SSL config: ${!!B}`,H.verbose),await n9({from:H.from||"localhost:5173",to:T,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:B,changeOrigin:H.changeOrigin||!1})}catch(T){G("proxies",`Failed to start proxy for ${H.to}: ${T}`,H.verbose),console.error(`Failed to start proxy for ${H.to}:`,T),z()}}function c9($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${h0.green(h0.bold("rpx"))} ${h0.green(`v${Bq}`)}`),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`)}SZ();var EL=new Hw("rpx",{showTags:!1});function p9($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}v$.chdir(Gq(fq(Tq(import.meta.url)),".."));var d$=new sY("rpx"),t9="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 l9(vw);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 g9(w)});d$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=p9(vw)?vw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):vw.to===$?vw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),v$.exit(1);try{await QY.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 QY.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 QY.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("--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 L9({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,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 V9({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??Z0(),A=await Ew(w),J=await DY(w),Y=$.registryDir,U=await Q9(Y).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:jw(w),rpxDir:w,registryDir:Y??Iw(),entries:U},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${jw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${jw(w)}`);if(console.log(`registry: ${Y??Iw()}`),U.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${U.length}):`);for(let Z of U){let B=Z.pid!==void 0?`, pid=${Z.pid}`:"";console.log(` https://${Z.to} \u2192 ${Z.from} (id=${Z.id}${B})`)}});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(!N1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),v$.exit(1);try{await _9({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 y9({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(!N1($))console.error(`invalid id: ${JSON.stringify($)}`),v$.exit(1);let A=await ZW($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await D9($,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??Z0();if(await DY(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await S9({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});d$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(t9)});d$.version(t9);d$.help();d$.run();
|