@stacksjs/rpx 0.11.10 → 0.11.12
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 +53 -53
- package/dist/{chunk-krj531r2.js → chunk-1j4gp3f8.js} +1 -1
- package/dist/{chunk-3yvvmvc0.js → chunk-747af2w4.js} +1 -1
- package/dist/{chunk-ppbddztz.js → chunk-9dndasyk.js} +2 -2
- package/dist/{chunk-97manwts.js → chunk-zs1tyy8z.js} +1 -1
- package/dist/hosts.d.ts +2 -0
- package/dist/index.js +6 -6
- package/package.json +1 -1
- package/src/hosts.ts +26 -5
- package/src/utils.ts +7 -1
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 iF}from"node:module";var xF=Object.defineProperty;var PF=($)=>$;function bF($,w){this[$]=PF.bind(null,w)}var JZ=($,w)=>{for(var A in w)xF($,A,{get:w[A],enumerable:!0,configurable:!0,set:bF.bind(w,A)})};var X$=($,w)=>()=>($&&(w=$($=0)),w);var i=iF(import.meta.url);import{existsSync as NZ,statSync as RZ}from"fs";import{existsSync as mj,mkdirSync as b5,readdirSync as i5,readFileSync as dj,writeFileSync as c5}from"fs";import{homedir as Iw}from"os";import{dirname as n5,resolve as a$}from"path";import cA from"process";import{existsSync as KZ,statSync as MZ}from"fs";import{existsSync as WY,mkdirSync as gj,readdirSync as lj,writeFileSync as tj}from"fs";import{homedir as Cw}from"os";import{dirname as IZ,resolve as D$}from"path";import fw from"process";import{join as pj,relative as rj,resolve as CZ}from"path";import LA from"process";import{existsSync as ZW,mkdirSync as o5,readdirSync as e5,writeFileSync as $6}from"fs";import{homedir as mU}from"os";import{dirname as J6,resolve as _$}from"path";import K1 from"process";import{join as aj,relative as sj,resolve as yZ}from"path";import SA from"process";import{existsSync as WW,mkdirSync as W6,readdirSync as E6,writeFileSync as B6}from"fs";import{dirname as F6,resolve as VA}from"path";import EY from"process";import{Buffer as l0}from"buffer";import{createCipheriv as oj,createDecipheriv as ej,randomBytes as dU}from"crypto";import{closeSync as gU,createReadStream as LZ,createWriteStream as $z,existsSync as lU,fsyncSync as SZ,openSync as VZ,writeFileSync as wz}from"fs";import{access as Az,constants as OZ,mkdir as Jz,readdir as fA,rename as XZ,stat as yw,unlink as ZA,writeFile as tU}from"fs/promises";import{join as Lw}from"path";import R$ from"process";import{pipeline as Uz}from"stream/promises";import{createGzip as _Z}from"zlib";import Sw from"process";import I0 from"process";import{Buffer as R0}from"buffer";import{createCipheriv as Yz,createDecipheriv as fz,randomBytes as pU}from"crypto";import{closeSync as rU,createReadStream as DZ,createWriteStream as Zz,existsSync as WA,fsyncSync as kZ,openSync as QZ,writeFileSync as Wz}from"fs";import{access as Ez,constants as xZ,mkdir as Bz,readdir as EA,rename as PZ,stat as Vw,unlink as BA,writeFile as aU}from"fs/promises";import{isAbsolute as hz,join as Ow,resolve as Fz}from"path";import V from"process";import{pipeline as jz}from"stream/promises";import{createGzip as bZ}from"zlib";import Xw from"process";import C0 from"process";import hA from"process";import{existsSync as FA}from"fs";import{resolve as sU}from"path";import{existsSync as zz}from"fs";import{existsSync as Hz,readdirSync as Tz}from"fs";import{extname as oU,resolve as iZ}from"path";import Gz from"process";import{join as qz,relative as Nz,resolve as cZ}from"path";import OA from"process";import{Buffer as K0}from"buffer";import{createCipheriv as Rz,createDecipheriv as Kz,randomBytes as eU}from"crypto";import{closeSync as $Y,createReadStream as uZ,createWriteStream as Mz,existsSync as jA,fsyncSync as vZ,openSync as nZ,writeFileSync as Iz}from"fs";import{access as Cz,constants as mZ,mkdir as yz,readdir as zA,rename as dZ,stat as _w,unlink as HA,writeFile as wY}from"fs/promises";import{isAbsolute as Lz,join as Dw,resolve as Sz}from"path";import O from"process";import{pipeline as Vz}from"stream/promises";import{createGzip as gZ}from"zlib";import kw from"process";import y0 from"process";import GA from"process";import{existsSync as qA}from"fs";import{resolve as ZY}from"path";import{existsSync as p9}from"fs";class YW{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(!NZ($))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=NZ(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 fW{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 _z($,w){this[$]=Xz.bind(null,w)}class KY{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 MZ($).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)?MZ(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 MY{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 Qz($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function xz($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function Pz($){return $.getStats().size*2}function IY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let J=[...w];for(let U of $)if(p(U)&&"name"in U){if(!J.find((f)=>p(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((f)=>p(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>XA(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(!p(w)||!p($))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(p(U)&&p(A[J]))A[J]=IY(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&p(U[0])&&p(A[J][0])){let Y=[...U];for(let f of A[J])if(p(f)&&"name"in f){if(!Y.find((Z)=>p(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(p(f)&&"path"in f){if(!Y.find((Z)=>p(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>XA(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 XA($,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(!XA($[A],w[A]))return!1;return!0}if(p($)&&p(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(!XA($[U],w[U]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function bz($,w){if(!WW($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return IY(w,J)}catch{return null}}catch{return null}}async function iz({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=VA(J,`${f}${W}`),E=await bz(Z,A);if(E!==null)return E}try{let f=VA(J,"package.json");if(WW(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return IY(A,Z)}catch{}}}catch{}return A}function cz($,w={}){let A=SA.cwd();while(A.includes("storage"))A=yZ(A,"..");let J=yZ(A,$||"");if(w?.relative)return sj(SA.cwd(),J);return J}async function uz(){try{let $=await iz({name:"clarity",defaultConfig:KA,cwd:SA.cwd(),endpoint:"",headers:{}});return{...KA,...$}}catch{return KA}}function e(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vz(){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 BW{async format($){let w=await vz(),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:Sw.pid,hostname:w(),environment:Sw.env.NODE_ENV||"development",platform:Sw.platform,version:Sw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Sw.env.NODE_ENV||Sw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class _A{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={...hY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new BW,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 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{...MA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...MA};return{...MA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:hY.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 Az(this.config.logDirectory,OZ.F_OK|OZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Jz(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l0.from($);try{if(!lU(this.currentLogFile))await tU(this.currentLogFile,"",{mode:420});if(U=VZ(this.currentLogFile,"a",420),wz(U,Z,{flag:"a"}),SZ(U),U!==void 0)gU(U),U=void 0;if((await yw(this.currentLogFile)).size===0){if(await tU(this.currentLogFile,Z,{flag:"w",mode:420}),(await yw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{gU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 Lw(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 Lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Lw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(e())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 dU(16).toString("hex")}generateKey(){return dU(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=dU(16),J=oj("aes-256-gcm",w,A),U=l0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:l0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=_Z(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(l0.from(l0.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(e())return;let $=await yw(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 fA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await yw(A).catch(()=>null))try{if(await XZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await ZA(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 yw(A).catch(()=>null))await XZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await fA(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await ZA(Lw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=LZ($),J=$z(w),U=_Z();await Uz(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()})),lU(this.currentLogFile))try{let $=VZ(this.currentLogFile,"r+");SZ($),gU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await fA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await ZA(Lw(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?d.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=R$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${d.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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&&!e()){let E=RW[$],B=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",h;switch($){case"debug":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:d.gray(f),level:$}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:d.green(f),level:$}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h),W){let j=W.split(`
|
|
4
|
+
import{createRequire as cF}from"node:module";var PF=Object.defineProperty;var bF=($)=>$;function iF($,w){this[$]=bF.bind(null,w)}var JZ=($,w)=>{for(var A in w)PF($,A,{get:w[A],enumerable:!0,configurable:!0,set:iF.bind(w,A)})};var X$=($,w)=>()=>($&&(w=$($=0)),w);var i=cF(import.meta.url);import{existsSync as NZ,statSync as RZ}from"fs";import{existsSync as dj,mkdirSync as v5,readdirSync as n5,readFileSync as gj,writeFileSync as m5}from"fs";import{homedir as Iw}from"os";import{dirname as l5,resolve as a$}from"path";import cA from"process";import{existsSync as KZ,statSync as MZ}from"fs";import{existsSync as WY,mkdirSync as lj,readdirSync as tj,writeFileSync as pj}from"fs";import{homedir as Cw}from"os";import{dirname as IZ,resolve as D$}from"path";import fw from"process";import{join as rj,relative as aj,resolve as CZ}from"path";import LA from"process";import{existsSync as ZW,mkdirSync as A6,readdirSync as J6,writeFileSync as U6}from"fs";import{homedir as mU}from"os";import{dirname as Z6,resolve as _$}from"path";import K1 from"process";import{join as sj,relative as oj,resolve as yZ}from"path";import SA from"process";import{existsSync as WW,mkdirSync as F6,readdirSync as j6,writeFileSync as z6}from"fs";import{dirname as T6,resolve as VA}from"path";import EY from"process";import{Buffer as l0}from"buffer";import{createCipheriv as ej,createDecipheriv as $z,randomBytes as dU}from"crypto";import{closeSync as gU,createReadStream as LZ,createWriteStream as wz,existsSync as lU,fsyncSync as SZ,openSync as VZ,writeFileSync as Az}from"fs";import{access as Jz,constants as OZ,mkdir as Uz,readdir as fA,rename as XZ,stat as yw,unlink as ZA,writeFile as tU}from"fs/promises";import{join as Lw}from"path";import R$ from"process";import{pipeline as Yz}from"stream/promises";import{createGzip as _Z}from"zlib";import Sw from"process";import I0 from"process";import{Buffer as R0}from"buffer";import{createCipheriv as fz,createDecipheriv as Zz,randomBytes as pU}from"crypto";import{closeSync as rU,createReadStream as DZ,createWriteStream as Wz,existsSync as WA,fsyncSync as kZ,openSync as QZ,writeFileSync as Ez}from"fs";import{access as Bz,constants as xZ,mkdir as hz,readdir as EA,rename as PZ,stat as Vw,unlink as BA,writeFile as aU}from"fs/promises";import{isAbsolute as Fz,join as Ow,resolve as jz}from"path";import V from"process";import{pipeline as zz}from"stream/promises";import{createGzip as bZ}from"zlib";import Xw from"process";import C0 from"process";import hA from"process";import{existsSync as FA}from"fs";import{resolve as sU}from"path";import{existsSync as Hz}from"fs";import{existsSync as Tz,readdirSync as Gz}from"fs";import{extname as oU,resolve as iZ}from"path";import qz from"process";import{join as Nz,relative as Rz,resolve as cZ}from"path";import OA from"process";import{Buffer as K0}from"buffer";import{createCipheriv as Kz,createDecipheriv as Mz,randomBytes as eU}from"crypto";import{closeSync as $Y,createReadStream as uZ,createWriteStream as Iz,existsSync as jA,fsyncSync as vZ,openSync as nZ,writeFileSync as Cz}from"fs";import{access as yz,constants as mZ,mkdir as Lz,readdir as zA,rename as dZ,stat as _w,unlink as HA,writeFile as wY}from"fs/promises";import{isAbsolute as Sz,join as Dw,resolve as Vz}from"path";import O from"process";import{pipeline as Oz}from"stream/promises";import{createGzip as gZ}from"zlib";import kw from"process";import y0 from"process";import GA from"process";import{existsSync as qA}from"fs";import{resolve as ZY}from"path";import{existsSync as r9}from"fs";class YW{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(!NZ($))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=NZ(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 fW{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 Dz($,w){this[$]=_z.bind(null,w)}class KY{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 MZ($).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)?MZ(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 MY{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 xz($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function Pz($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function bz($){return $.getStats().size*2}function IY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let J=[...w];for(let U of $)if(p(U)&&"name"in U){if(!J.find((f)=>p(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((f)=>p(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>XA(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(!p(w)||!p($))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(p(U)&&p(A[J]))A[J]=IY(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&p(U[0])&&p(A[J][0])){let Y=[...U];for(let f of A[J])if(p(f)&&"name"in f){if(!Y.find((Z)=>p(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(p(f)&&"path"in f){if(!Y.find((Z)=>p(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>XA(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 XA($,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(!XA($[A],w[A]))return!1;return!0}if(p($)&&p(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(!XA($[U],w[U]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iz($,w){if(!WW($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return IY(w,J)}catch{return null}}catch{return null}}async function cz({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=VA(J,`${f}${W}`),E=await iz(Z,A);if(E!==null)return E}try{let f=VA(J,"package.json");if(WW(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return IY(A,Z)}catch{}}}catch{}return A}function uz($,w={}){let A=SA.cwd();while(A.includes("storage"))A=yZ(A,"..");let J=yZ(A,$||"");if(w?.relative)return oj(SA.cwd(),J);return J}async function vz(){try{let $=await cz({name:"clarity",defaultConfig:KA,cwd:SA.cwd(),endpoint:"",headers:{}});return{...KA,...$}}catch{return KA}}function e(){if(I0.env.NODE_ENV==="test"||I0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nz(){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 BW{async format($){let w=await nz(),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:Sw.pid,hostname:w(),environment:Sw.env.NODE_ENV||"development",platform:Sw.platform,version:Sw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Sw.env.NODE_ENV||Sw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class _A{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={...hY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new BW,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 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{...MA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...MA};return{...MA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:hY.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 Jz(this.config.logDirectory,OZ.F_OK|OZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Uz(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l0.from($);try{if(!lU(this.currentLogFile))await tU(this.currentLogFile,"",{mode:420});if(U=VZ(this.currentLogFile,"a",420),Az(U,Z,{flag:"a"}),SZ(U),U!==void 0)gU(U),U=void 0;if((await yw(this.currentLogFile)).size===0){if(await tU(this.currentLogFile,Z,{flag:"w",mode:420}),(await yw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{gU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 Lw(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 Lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Lw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(e())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 dU(16).toString("hex")}generateKey(){return dU(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=dU(16),J=ej("aes-256-gcm",w,A),U=l0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:l0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=_Z(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(l0.from(l0.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(e())return;let $=await yw(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 fA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await yw(A).catch(()=>null))try{if(await XZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await ZA(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 yw(A).catch(()=>null))await XZ(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await fA(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await ZA(Lw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=LZ($),J=wz(w),U=_Z();await Yz(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()})),lU(this.currentLogFile))try{let $=VZ(this.currentLogFile,"r+");SZ($),gU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!e()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await fA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await ZA(Lw(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?d.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=R$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${d.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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&&!e()){let E=RW[$],B=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",h;switch($){case"debug":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:d.gray(f),level:$}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:d.green(f),level:$}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h),W){let j=W.split(`
|
|
5
5
|
`);for(let F of j)if(F.trim()&&!F.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:d.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!e()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}if(!this.shouldLog($))return;let Z=`${Y} ${this.environment}.${$.toUpperCase()}: ${f}
|
|
6
6
|
`;if(W)Z+=`${W}
|
|
7
7
|
`;Z=Z.replace(this.ANSI_PATTERN,""),await this.writeToFile(Z)}time($){let w=performance.now();if(this.fancy&&!e()){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:d.blue("◐"),tag:A,message:`${d.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
8
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!e()){let B=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:d.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!e())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 _A(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(!lU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return LZ(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"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W
|
|
8
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!e()){let B=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:d.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!e())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 _A(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(!lU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return LZ(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"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W=$z("aes-256-gcm",A,U);return W.setAuthTag(Y),l0.concat([W.update(f),W.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return 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);if(this.fancy&&!e()){let Y=$.split(`
|
|
9
9
|
`),f=Math.max(...Y.map((B)=>B.length))+2,W=`┌${"─".repeat(f)}┐`,Z=`└${"─".repeat(f)}┘`,E=Y.map((B)=>{let h=" ".repeat(f-B.length-2);return`│ ${B}${h} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:d.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(W)})),E.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:d.cyan(Z),showTimestamp:!1}))}else if(!e())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let U=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
10
10
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(e())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${d.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=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(U==="y"||U==="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 f=/%([sdijfo%])/g,W=0;if(A=$.replace(f,(Z,E)=>{if(E==="%")return"%";if(W>=w.length)return Z;let B=w[W++];switch(E){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 Z}}),W<w.length)A+=` ${w.slice(W).map((Z)=>typeof Z==="object"?JSON.stringify(Z,null,2):String(Z)).join(" ")}`}if(this.fancy&&!e()){let f=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",W=d.blue("◐");console.error(`${W} ${f} ${d.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
11
11
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||e()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(f,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,f)),W!==void 0)this.activeProgressBar.message=W;let Z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Z)},finish:(f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;if(this.activeProgressBar.current=this.activeProgressBar.total,f!==void 0)this.activeProgressBar.message=f;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(f,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||e())return;R$.stdout.write(`${"\r".padEnd(R$.stdout.columns||80)}\r`),this.log(W,f),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||e()||!R$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=d.green("━".repeat(J)),f=d.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=w||A===100?d.green("✓"):d.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=R$.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,R$.stdout.write($.lastRenderedLine),w)R$.stdout.write(`
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||e()||!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(e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await fA(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=Lw(this.config.logDirectory,J);if($.before)try{if((await yw(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 ZA(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&&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 U of $)if(c(U)&&"name"in U){if(!J.find((f)=>c(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(c(U)&&"path"in U){if(!J.find((f)=>c(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>DA(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(!c(w)||!c($))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(c(U)&&c(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&&c(U[0])&&c(A[J][0])){let Y=[...U];for(let f of A[J])if(c(f)&&"name"in f){if(!Y.find((Z)=>c(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(c(f)&&"path"in f){if(!Y.find((Z)=>c(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>DA(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(!c(w)||!c($))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(c(Y)&&c(f))J[U]=CY(f,Y,A);else J[U]=Y}return J}function DA($,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(!DA($[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 U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!DA($[U],w[U]))return!1}return!0}return!1}function c($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function TA($,w,A="replace"){if(!ZW($))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 nz($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${J}_${h.map(j).join("_")}`,T=`${J}_${h.map((H)=>H.toUpperCase()).join("_")}`;if(A)M$.info(`Checking environment variable ${F} for config ${$}.${h.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))Z[E]=Y(B,h);else{let H=K1.env[F]||K1.env[T];if(H!==void 0){if(A)M$.info(`Using environment variable ${H?F:T} for config ${$}.${h.join(".")}`);if(typeof B==="number")Z[E]=Number(H);else if(typeof B==="boolean")Z[E]=H.toLowerCase()==="true";else if(Array.isArray(B))try{let G=JSON.parse(H);if(Array.isArray(G))Z[E]=G;else Z[E]=H.split(",").map((q)=>q.trim())}catch{Z[E]=H.split(",").map((G)=>G.trim())}else Z[E]=H}}}return Z}return Y(U)}async function mz({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)?nz($,U,Y):U,E=A||K1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(Y)M$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let h=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,_$(E,"config"),_$(E,".config"),J?_$(E,J):void 0].filter(Boolean)));for(let G of H){if(Y)M$.info(`Searching for configuration in: ${G}`);let N=[_$(E,"config"),_$(E,".config")].concat(J?[_$(E,J)]:[]).includes(G)?[...h,...j,...F,...T]:[...j,...h,...T,...F];for(let K of N)for(let C of B){let y=_$(G,`${K}${C}`),S=await TA(y,Z,W);if(S!==null){if(Y)M$.success(`Configuration loaded from: ${y}`);return S}}}if($){let G=_$(mU(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)M$.info(`Checking user config directory: ${G}`);for(let N of q)for(let K of B){let C=_$(G,`${N}${K}`),y=await TA(C,Z,W);if(y!==null){if(Y)M$.success(`Configuration loaded from user config directory: ${C}`);return y}}}if($){let G=_$(mU(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)M$.info(`Checking user config directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=_$(G,`${N}${K}`),y=await TA(C,Z,W);if(y!==null){if(Y)M$.success(`Configuration loaded from user config directory dotfile: ${C}`);return y}}}if($){let G=mU(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)M$.info(`Checking user home directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=_$(G,`${N}${K}`),y=await TA(C,Z,W);if(y!==null){if(Y)M$.success(`Configuration loaded from user home directory: ${C}`);return y}}}try{let G=_$(E,"package.json");if(ZW(G)){let q=await import(G),N=q[$];if(!N&&w){if(N=q[w],N&&Y)M$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)M$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return CY(Z,N,W)}catch(K){if(Y)M$.warn("Failed to merge package.json config:",K)}}}catch(G){if(Y)M$.warn("Failed to load package.json:",G)}if(Y)M$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function dz($,w={}){let A=LA.cwd();while(A.includes("storage"))A=CZ(A,"..");let J=CZ(A,$||"");if(w?.relative)return rj(LA.cwd(),J);return J}async function gz(){try{let $=await mz({name:"clarity",alias:"logging",defaultConfig:IA,cwd:LA.cwd()});return{...IA,...$||{}}}catch{return IA}}function Z$(){if(C0.env.NODE_ENV==="test"||C0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lz(){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 hW{async format($){let w=await lz(),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 kA{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 hW,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: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!Z$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await Ez(this.config.logDirectory,xZ.F_OK|xZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Bz(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!WA(this.currentLogFile))await aU(this.currentLogFile,"",{mode:420});if(U=QZ(this.currentLogFile,"a",420),Wz(U,Z,{flag:"a"}),kZ(U),U!==void 0)rU(U),U=void 0;if((await Vw(this.currentLogFile)).size===0){if(await aU(this.currentLogFile,Z,{flag:"w",mode:420}),(await Vw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{rU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 Ow(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ow(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Ow(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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((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 pU(16).toString("hex")}generateKey(){return pU(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=pU(16),J=Yz("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(),E=R0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=bZ(),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(Z$())return;if(!this.shouldWriteToFile())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 EA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),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 PZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await BA(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 aU(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 PZ(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 BA(Ow(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=DZ($),J=Zz(w),U=bZ();await jz(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()})),WA(this.currentLogFile))try{let $=QZ(this.currentLogFile,"r+");kZ($),rU($)}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 EA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await BA(Ow(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 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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=V.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${D.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(Z$())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(hz(w)||w.startsWith("./")||w.startsWith("../"))w=Fz(w);else return null;return WA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":KW[$],j=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:D.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:D.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||e()||!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(e()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await fA(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=Lw(this.config.logDirectory,J);if($.before)try{if((await yw(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 ZA(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&&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 U of $)if(c(U)&&"name"in U){if(!J.find((f)=>c(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(c(U)&&"path"in U){if(!J.find((f)=>c(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>DA(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(!c(w)||!c($))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(c(U)&&c(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&&c(U[0])&&c(A[J][0])){let Y=[...U];for(let f of A[J])if(c(f)&&"name"in f){if(!Y.find((Z)=>c(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(c(f)&&"path"in f){if(!Y.find((Z)=>c(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>DA(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(!c(w)||!c($))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(c(Y)&&c(f))J[U]=CY(f,Y,A);else J[U]=Y}return J}function DA($,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(!DA($[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 U of A){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!DA($[U],w[U]))return!1}return!0}return!1}function c($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function TA($,w,A="replace"){if(!ZW($))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 mz($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${J}_${h.map(j).join("_")}`,T=`${J}_${h.map((H)=>H.toUpperCase()).join("_")}`;if(A)M$.info(`Checking environment variable ${F} for config ${$}.${h.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))Z[E]=Y(B,h);else{let H=K1.env[F]||K1.env[T];if(H!==void 0){if(A)M$.info(`Using environment variable ${H?F:T} for config ${$}.${h.join(".")}`);if(typeof B==="number")Z[E]=Number(H);else if(typeof B==="boolean")Z[E]=H.toLowerCase()==="true";else if(Array.isArray(B))try{let G=JSON.parse(H);if(Array.isArray(G))Z[E]=G;else Z[E]=H.split(",").map((q)=>q.trim())}catch{Z[E]=H.split(",").map((G)=>G.trim())}else Z[E]=H}}}return Z}return Y(U)}async function dz({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)?mz($,U,Y):U,E=A||K1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(Y)M$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let h=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,_$(E,"config"),_$(E,".config"),J?_$(E,J):void 0].filter(Boolean)));for(let G of H){if(Y)M$.info(`Searching for configuration in: ${G}`);let N=[_$(E,"config"),_$(E,".config")].concat(J?[_$(E,J)]:[]).includes(G)?[...h,...j,...F,...T]:[...j,...h,...T,...F];for(let K of N)for(let C of B){let y=_$(G,`${K}${C}`),S=await TA(y,Z,W);if(S!==null){if(Y)M$.success(`Configuration loaded from: ${y}`);return S}}}if($){let G=_$(mU(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)M$.info(`Checking user config directory: ${G}`);for(let N of q)for(let K of B){let C=_$(G,`${N}${K}`),y=await TA(C,Z,W);if(y!==null){if(Y)M$.success(`Configuration loaded from user config directory: ${C}`);return y}}}if($){let G=_$(mU(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)M$.info(`Checking user config directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=_$(G,`${N}${K}`),y=await TA(C,Z,W);if(y!==null){if(Y)M$.success(`Configuration loaded from user config directory dotfile: ${C}`);return y}}}if($){let G=mU(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)M$.info(`Checking user home directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=_$(G,`${N}${K}`),y=await TA(C,Z,W);if(y!==null){if(Y)M$.success(`Configuration loaded from user home directory: ${C}`);return y}}}try{let G=_$(E,"package.json");if(ZW(G)){let q=await import(G),N=q[$];if(!N&&w){if(N=q[w],N&&Y)M$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)M$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return CY(Z,N,W)}catch(K){if(Y)M$.warn("Failed to merge package.json config:",K)}}}catch(G){if(Y)M$.warn("Failed to load package.json:",G)}if(Y)M$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function gz($,w={}){let A=LA.cwd();while(A.includes("storage"))A=CZ(A,"..");let J=CZ(A,$||"");if(w?.relative)return aj(LA.cwd(),J);return J}async function lz(){try{let $=await dz({name:"clarity",alias:"logging",defaultConfig:IA,cwd:LA.cwd()});return{...IA,...$||{}}}catch{return IA}}function Z$(){if(C0.env.NODE_ENV==="test"||C0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tz(){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 hW{async format($){let w=await tz(),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 kA{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 hW,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: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!Z$()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await Bz(this.config.logDirectory,xZ.F_OK|xZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await hz(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:R0.from($);try{if(!WA(this.currentLogFile))await aU(this.currentLogFile,"",{mode:420});if(U=QZ(this.currentLogFile,"a",420),Ez(U,Z,{flag:"a"}),kZ(U),U!==void 0)rU(U),U=void 0;if((await Vw(this.currentLogFile)).size===0){if(await aU(this.currentLogFile,Z,{flag:"w",mode:420}),(await Vw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{rU(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 Ow(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ow(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Ow(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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((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 pU(16).toString("hex")}generateKey(){return pU(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=pU(16),J=fz("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(),E=R0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=bZ(),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(Z$())return;if(!this.shouldWriteToFile())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 EA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),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 PZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await BA(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 aU(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 PZ(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 BA(Ow(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=DZ($),J=Wz(w),U=bZ();await zz(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()})),WA(this.currentLogFile))try{let $=QZ(this.currentLogFile,"r+");kZ($),rU($)}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 EA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await BA(Ow(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 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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=V.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${D.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(Z$())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(Fz(w)||w.startsWith("./")||w.startsWith("../"))w=jz(w);else return null;return WA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":KW[$],j=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:D.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:D.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
13
13
|
`);for(let H of T)if(H.trim()&&!H.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:D.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!Z$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}if(!this.shouldLog($))return;let B=`${Y} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
14
14
|
`;if(W)B+=`${W}
|
|
15
15
|
`;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,w=""){let A={update:(W,Z)=>{},finish:(W)=>{},interrupt:(W,Z)=>{}};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$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Z!==void 0)this.activeProgressBar.message=Z;if(this.shouldStyleConsole()&&!Z$()&&V.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Z="info")=>{if(!Z$()&&V.stdout.isTTY)V.stdout.write(`
|
|
16
16
|
`);if(this[Z==="warning"?"warn":Z](W),this.activeProgressBar&&this.shouldStyleConsole()&&!Z$()&&V.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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
17
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":D.green("✓"),tag:B,message:`${Y}${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 kA(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(!WA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return DZ(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=R0.isBuffer($)?$:R0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=
|
|
17
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":D.green("✓"),tag:B,message:`${Y}${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 kA(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(!WA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return DZ(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=R0.isBuffer($)?$:R0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=Zz("aes-256-gcm",A,U);W.setAuthTag(Y);let Z=W.update(f),E=W.final(),B=Z.length+E.length,h=R0.allocUnsafe(B);return Z.copy(h,0),E.copy(h,Z.length),h.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:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
18
18
|
`),Z=Math.max(...W.map((j)=>j.length))+2,E=`┌${"─".repeat(Z)}┐`,B=`└${"─".repeat(Z)}┘`,h=W.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:D.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:D.cyan(E),showTimestamp:!1})),h.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:D.cyan(B),showTimestamp:!1}))}else if(!Z$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
19
19
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(Z$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${D.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=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(U==="y"||U==="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,E=0;if(A=$.replace(Z,(B,h)=>{if(h==="%")return"%";if(E>=w.length)return B;let j=w[E++];switch(h){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 B}}),E<w.length)A+=` ${w.slice(E).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?D.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${D.blue("◐")} `;console.error(`${E}${Z} ${D.cyan(J)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
20
20
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!V.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=D.green("━".repeat(J)),f=D.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":w||A===100?D.green("✓"):D.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${D.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=V.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,V.stdout.write($.lastRenderedLine),w)V.stdout.write(`
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Z$()||!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(Z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EA(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=Ow(this.config.logDirectory,J);if($.before)try{if((await Vw(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 BA(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)}}}async function FW($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function jW($){return $ instanceof
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Z$()||!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(Z$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EA(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=Ow(this.config.logDirectory,J);if($.before)try{if((await Vw(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 BA(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)}}}async function FW($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function jW($){return $ instanceof m$}function pz($){return $ instanceof QA}function rz($){if(jW($))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 uA{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:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:W=!1,trackPerformance:Z=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let B=J||this.generateEnvPrefix($),h={...w};return this.processObject(h,[],B,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:W,configName:$}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(Z)return C1.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[U,Y]of Object.entries($)){let f=[...w,U],W=f.map((B)=>this.formatEnvKey(B,J.useCamelCase)),Z=`${A}_${W.join("_")}`,E=J.useBackwardCompatibility?`${A}_${f.map((B)=>B.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let B=hA.env[Z]||(E?hA.env[E]:void 0);if(B!==void 0){if(J.verbose){let h=hA.env[Z]?Z:E}try{$[U]=this.parseEnvironmentValue(B,typeof Y,Z,J.customParsers,J.configName)}catch(h){if(h instanceof xA)throw h;throw t0.envVar(Z,B,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw t0.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(hA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;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(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],W=`${A}_${f.map((Z)=>this.formatEnvKey(Z,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:W,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}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 iF}from"node:module";var xF=Object.defineProperty;var PF
|
|
|
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 rz($,w){let A=qW("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function zW($,w,A={}){return HW($,w,A,new WeakMap)}function HW($,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 TW($,w,U,J);if(!s$(w)||!s$($))return w;return ez($,w,A,J)}function TW($,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 az($,w);case"smart":return sz($,w,J);default:return w}return w}function az($,w){let A=[...w];for(let J of $)if(!A.some((U)=>BY(U,J)))A.push(J);return A}function sz($,w,A){if(w.length===0)return $;if($.length===0)return w;if(s$(w[0])&&s$($[0]))return oz($,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 oz($,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((E)=>s$(E)&&(W in E)&&E[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function ez($,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]=HW(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=TW(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function yY($,w,A="replace"){return zW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function BY($,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(!BY($[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(!BY($[U],w[U]))return!1}return!0}return!1}function s$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class vA{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 E=Qw.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!FA($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new M1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new M1($,Error("Configuration must export a valid object"),"unknown");let G={config:yY(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)Qw.setWithFileCheck("file",G,$,Y);return G}catch(E){throw E instanceof Error?t0.configLoad($,E):t0.configLoad($,Error(String(E)))}};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(sU(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 FW(async()=>{return FA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!FA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=sU($,`${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=sU($,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(!FA($))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 LY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await C1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!zz(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:IW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class SY{fileLoader=new vA;envProcessor=new uA;validator=new LY;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)f0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw f0.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:E="replace",verbose:B=!1}=$,h=Y||fw.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(D$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw t0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),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 E=W?R1($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)f0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)f0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?R1($,A,U):A,W=[D$(Cw(),".config",$),D$(Cw(),".config"),Cw()];for(let Z of W){if(U)f0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)f0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?R1($,J,Y):J;try{let Z=D$(A,"package.json");if(!WY(Z))return null;let E=await import(Z),B=E[$],h=$;if(!B&&w)B=E[w],h=w;if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)f0.success(`Configuration loaded from package.json: ${h}`);return{config:yY(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)f0.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:R1($,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 Qw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);Qw.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$(Cw(),".config",$),D$(Cw(),".config"),Cw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function lZ($){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 $9($){return L0.loadConfig({...$,__strictErrorHandling:!0})}async function GW($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await L0.loadConfig($);else J=await L0.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)f0.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 L0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function w9($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await L0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&lZ(A)))return(await L0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await L0.loadConfig({...$,cwd:$.cwd||fw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&lZ(w)))return(await L0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function A9($,w,A="replace"){let J=new vA;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function R1($,w,A=!1){let J=new uA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=fw.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function J9($){let w=D$(fw.cwd(),$.configDir),A=D$(fw.cwd(),$.generatedDir),J=D$(A,"config-types.ts");if(!WY(IZ(J)))gj(IZ(J),{recursive:!0,mode:511});let U=WY(w)?lj(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${D9}
|
|
33
|
+
`;return A}}function az($,w){let A=qW("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function zW($,w,A={}){return HW($,w,A,new WeakMap)}function HW($,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 TW($,w,U,J);if(!s$(w)||!s$($))return w;return $9($,w,A,J)}function TW($,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 sz($,w);case"smart":return oz($,w,J);default:return w}return w}function sz($,w){let A=[...w];for(let J of $)if(!A.some((U)=>BY(U,J)))A.push(J);return A}function oz($,w,A){if(w.length===0)return $;if($.length===0)return w;if(s$(w[0])&&s$($[0]))return ez($,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 ez($,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((E)=>s$(E)&&(W in E)&&E[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function $9($,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]=HW(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=TW(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function yY($,w,A="replace"){return zW($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function BY($,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(!BY($[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(!BY($[U],w[U]))return!1}return!0}return!1}function s$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class vA{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 E=Qw.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!FA($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new M1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new M1($,Error("Configuration must export a valid object"),"unknown");let G={config:yY(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)Qw.setWithFileCheck("file",G,$,Y);return G}catch(E){throw E instanceof Error?t0.configLoad($,E):t0.configLoad($,Error(String(E)))}};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(sU(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 FW(async()=>{return FA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!FA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=sU($,`${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=sU($,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(!FA($))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 LY{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await C1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!Hz(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:IW},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class SY{fileLoader=new vA;envProcessor=new uA;validator=new LY;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)f0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw f0.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:E="replace",verbose:B=!1}=$,h=Y||fw.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(D$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw t0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),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 E=W?R1($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)f0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)f0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?R1($,A,U):A,W=[D$(Cw(),".config",$),D$(Cw(),".config"),Cw()];for(let Z of W){if(U)f0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)f0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?R1($,J,Y):J;try{let Z=D$(A,"package.json");if(!WY(Z))return null;let E=await import(Z),B=E[$],h=$;if(!B&&w)B=E[w],h=w;if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)f0.success(`Configuration loaded from package.json: ${h}`);return{config:yY(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)f0.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:R1($,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 Qw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);Qw.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$(Cw(),".config",$),D$(Cw(),".config"),Cw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function lZ($){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 w9($){return L0.loadConfig({...$,__strictErrorHandling:!0})}async function GW($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await L0.loadConfig($);else J=await L0.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)f0.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 L0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function A9($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await L0.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&lZ(A)))return(await L0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await L0.loadConfig({...$,cwd:$.cwd||fw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&lZ(w)))return(await L0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function J9($,w,A="replace"){let J=new vA;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function R1($,w,A=!1){let J=new uA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=fw.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function U9($){let w=D$(fw.cwd(),$.configDir),A=D$(fw.cwd(),$.generatedDir),J=D$(A,"config-types.ts");if(!WY(IZ(J)))lj(IZ(J),{recursive:!0,mode:511});let U=WY(w)?tj(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${k9}
|
|
34
34
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
35
|
-
`;
|
|
35
|
+
`;pj(J,Y,{mode:438})}function Y9($){let w=null,A=null,J=()=>{if(!A)A=GW($).then((Y)=>{return w=Y,Y},(Y)=>{let f="defaultConfig"in $?$.defaultConfig:{};if(w=f,"verbose"in $&&$.verbose)f0.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return f});return A},U="defaultConfig"in $?$.defaultConfig:{};return w=U,J(),new Proxy({},{get(Y,f){if(w)return w[f];let W=U[f];return J(),W},has(Y,f){return f in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(Y,f){return Object.getOwnPropertyDescriptor(w||U,f)},set(Y,f,W){if(!w)w={...U};return w[f]=W,!0}})}function f9($){let w=iZ(qz.cwd(),$?.configDir||"./config");function A(){if(!Tz(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],f=Gz(w).filter((Z)=>U.has(oU(Z))).map((Z)=>({base:Z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Z})),W=new Map;for(let{base:Z,file:E}of f){let B=oU(E).toLowerCase(),h=W.get(Z);if(!h){W.set(Z,E);continue}let j=oU(h).toLowerCase();if(Y.indexOf(B)<Y.indexOf(j))W.set(Z,E)}return Array.from(W.entries()).map(([Z,E])=>({base:Z,file:E})).sort((Z,E)=>Z.base.localeCompare(E.base))}function J(){let U=A(),Y=U.map((E)=>E.base),f=Y.length?Y.map((E)=>`'${E}'`).join(" | "):"string",W=U.length?`{
|
|
36
36
|
${U.map((E)=>{let B=iZ(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${B}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
38
|
}`:"Record<string, any>";return`export type ConfigNames = ${f}
|
|
39
39
|
export type ConfigByName = ${W}
|
|
40
40
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
41
41
|
export type ConfigOf = Config
|
|
42
|
-
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(Y)=>{return{path:Y.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:J(),loader:"ts"}})}}}function Q9($,w={}){let A=OA.cwd();while(A.includes("storage"))A=cZ(A,"..");let J=cZ(A,$||"");if(w?.relative)return Nz(OA.cwd(),J);return J}function E$(){if(y0.env.NODE_ENV==="test"||y0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function P9(){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 SW{async format($){let w=await P9(),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:kw.pid,hostname:w(),environment:kw.env.NODE_ENV||"development",platform:kw.platform,version:kw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:kw.env.NODE_ENV||kw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new SW,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{...fY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...fY};return{...fY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},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 A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await Cz(this.config.logDirectory,mZ.F_OK|mZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await yz(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:K0.from($);try{if(!jA(this.currentLogFile))await wY(this.currentLogFile,"",{mode:420});if(U=nZ(this.currentLogFile,"a",420),Iz(U,Z,{flag:"a"}),vZ(U),U!==void 0)$Y(U),U=void 0;if((await _w(this.currentLogFile)).size===0){if(await wY(this.currentLogFile,Z,{flag:"w",mode:420}),(await _w(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{$Y(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 Dw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Dw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Dw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,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 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=Rz("aes-256-gcm",w,A),U=K0.isBuffer($)?$:K0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),E=K0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=gZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(K0.from(K0.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(E$())return;if(!this.shouldWriteToFile())return;let $=await _w(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,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await _w(A).catch(()=>null))try{if(await dZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await HA(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 wY(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 _w(A).catch(()=>null))await dZ(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 HA(Dw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=uZ($),J=Mz(w),U=gZ();await Vz(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()})),jA(this.currentLogFile))try{let $=nZ(this.currentLogFile,"r+");vZ($),$Y($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await zA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await HA(Dw(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()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E$())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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=O.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${x.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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=x.underline(x.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",E="\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)=>x.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>x.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>x.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>x.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>x.strikethrough(J)),w}supportsHyperlinks(){if(E$())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(Lz(w)||w.startsWith("./")||w.startsWith("../"))w=Sz(w);else return null;return jA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":v9[$],j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:x.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:x.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
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 x9($,w={}){let A=OA.cwd();while(A.includes("storage"))A=cZ(A,"..");let J=cZ(A,$||"");if(w?.relative)return Rz(OA.cwd(),J);return J}function E$(){if(y0.env.NODE_ENV==="test"||y0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function b9(){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 SW{async format($){let w=await b9(),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:kw.pid,hostname:w(),environment:kw.env.NODE_ENV||"development",platform:kw.platform,version:kw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:kw.env.NODE_ENV||kw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class nA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new SW,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{...fY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...fY};return{...fY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},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 A=(async()=>{let U,Y=0,f=3,W=1000;while(Y<f)try{try{try{await yz(this.config.logDirectory,mZ.F_OK|mZ.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await Lz(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:K0.from($);try{if(!jA(this.currentLogFile))await wY(this.currentLogFile,"",{mode:420});if(U=nZ(this.currentLogFile,"a",420),Cz(U,Z,{flag:"a"}),vZ(U),U!==void 0)$Y(U),U=void 0;if((await _w(this.currentLogFile)).size===0){if(await wY(this.currentLogFile,Z,{flag:"w",mode:420}),(await _w(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{$Y(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 Dw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Dw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return Dw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E$())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,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 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=Kz("aes-256-gcm",w,A),U=K0.isBuffer($)?$:K0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),E=K0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=gZ(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(K0.from(K0.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(E$())return;if(!this.shouldWriteToFile())return;let $=await _w(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,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await _w(A).catch(()=>null))try{if(await dZ(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await HA(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 wY(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 _w(A).catch(()=>null))await dZ(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 HA(Dw(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=uZ($),J=Iz(w),U=gZ();await Oz(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()})),jA(this.currentLogFile))try{let $=nZ(this.currentLogFile,"r+");vZ($),$Y($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E$()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await zA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await HA(Dw(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()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E$())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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=O.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${x.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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=x.underline(x.blue(J)),f=this.toAbsoluteFilePath(U);if(f&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(f)}`,Z="\x1B]8;;",E="\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)=>x.bgGray(J)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,J)=>x.bold(J)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,J)=>x.italic(J)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,J)=>x.italic(J)),w=w.replace(/~([^~]+)~/g,(A,J)=>x.strikethrough(J)),w}supportsHyperlinks(){if(E$())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(Sz(w)||w.startsWith("./")||w.startsWith("../"))w=Vz(w);else return null;return jA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":n9[$],j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:x.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:x.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
43
43
|
`);for(let H of T)if(H.trim()&&!H.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:x.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!E$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}let B=`${Y} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
44
44
|
`;if(W)B+=`${W}
|
|
45
45
|
`;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,w=""){let A={update:(W,Z)=>{},finish:(W)=>{},interrupt:(W,Z)=>{}};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$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Z!==void 0)this.activeProgressBar.message=Z;if(this.shouldStyleConsole()&&!E$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Z="info")=>{if(!E$()&&O.stdout.isTTY)O.stdout.write(`
|
|
46
46
|
`);if(this[Z==="warning"?"warn":Z](W),this.activeProgressBar&&this.shouldStyleConsole()&&!E$()&&O.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",J=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:J,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:A,message:`${x.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let J=performance.now(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
47
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":x.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!E$())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 nA(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(!jA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uZ(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=K0.isBuffer($)?$:K0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=
|
|
47
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":x.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!E$())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 nA(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(!jA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uZ(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=K0.isBuffer($)?$:K0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=Mz("aes-256-gcm",A,U);W.setAuthTag(Y);let Z=W.update(f),E=W.final(),B=Z.length+E.length,h=K0.allocUnsafe(B);return Z.copy(h,0),E.copy(h,Z.length),h.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:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
48
48
|
`),Z=Math.max(...W.map((j)=>j.length))+2,E=`┌${"─".repeat(Z)}┐`,B=`└${"─".repeat(Z)}┘`,h=W.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:x.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(E),showTimestamp:!1})),h.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:x.cyan(B),showTimestamp:!1}))}else if(!E$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
49
49
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(E$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${x.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=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(U==="y"||U==="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 Z=/%([sdijfo%])/g,E=0;if(A=$.replace(Z,(B,h)=>{if(h==="%")return"%";if(E>=w.length)return B;let j=w[E++];switch(h){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 B}}),E<w.length)A+=` ${w.slice(E).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${x.blue("◐")} `;console.error(`${E}${Z} ${x.cyan(J)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
50
50
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!O.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=x.green("━".repeat(J)),f=x.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":w||A===100?x.green("✓"):x.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=O.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,O.stdout.write($.lastRenderedLine),w)O.stdout.write(`
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E$()||!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(E$()){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=Dw(this.config.logDirectory,J);if($.before)try{if((await _w(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 HA(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)}}}async function
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E$()||!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(E$()){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=Dw(this.config.logDirectory,J);if($.before)try{if((await _w(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 HA(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)}}}async function m9($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}class OY{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:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:W=!1,trackPerformance:Z=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let B=J||this.generateEnvPrefix($),h={...w};return this.processObject(h,[],B,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:W,configName:$}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(Z)return RY.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[U,Y]of Object.entries($)){let f=[...w,U],W=f.map((B)=>this.formatEnvKey(B,J.useCamelCase)),Z=`${A}_${W.join("_")}`,E=J.useBackwardCompatibility?`${A}_${f.map((B)=>B.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let B=GA.env[Z]||(E?GA.env[E]:void 0);if(B!==void 0){if(J.verbose){let h=GA.env[Z]?Z:E}try{$[U]=this.parseEnvironmentValue(B,typeof Y,Z,J.customParsers,J.configName)}catch(h){if(h instanceof VY)throw h;throw xw.envVar(Z,B,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw xw.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(GA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;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(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],W=`${A}_${f.map((Z)=>this.formatEnvKey(Z,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:W,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}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 m9($,w,A={}){return xW($,w,A,new WeakMap)}function xW($,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 PW($,w,U,J);if(!o$(w)||!o$($))return w;return t9($,w,A,J)}function PW($,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 d9($,w);case"smart":return g9($,w,J);default:return w}return w}function d9($,w){let A=[...w];for(let J of $)if(!A.some((U)=>NY(U,J)))A.push(J);return A}function g9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return l9($,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 l9($,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((E)=>o$(E)&&(W in E)&&E[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function t9($,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]=xW(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=PW(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function bW($,w,A="replace"){return m9($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function NY($,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(!NY($[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(!NY($[U],w[U]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class iW{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 E=yA.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!qA($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new bA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new bA($,Error("Configuration must export a valid object"),"unknown");let G={config:bW(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)yA.setWithFileCheck("file",G,$,Y);return G}catch(E){throw E instanceof Error?xw.configLoad($,E):xw.configLoad($,Error(String(E)))}};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(ZY(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 n9(async()=>{return qA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!qA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=ZY($,`${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=ZY($,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(!qA($))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 cW{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await RY.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!p9(w))throw new iA(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 iA(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:r9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function a9($){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 uW{fileLoader=new iW;envProcessor=new OY;validator=new cW;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)M0.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 M0.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:E="replace",verbose:B=!1}=$,h=Y||cA.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(a$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw xw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),warnings:[`No configuration file found for "${J}"${a9(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let E=W?NA($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)M0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)M0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?NA($,A,U):A,W=[a$(Iw(),".config",$),a$(Iw(),".config"),Iw()];for(let Z of W){if(U)M0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)M0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?NA($,J,Y):J;try{let Z=a$(A,"package.json");if(!mj(Z))return null;let E={};try{E=JSON.parse(dj(Z,"utf8"))}catch(j){if(Y)M0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let B=E[$],h=$;if(!B&&w){let j=Array.isArray(w)?w:[w];for(let F of j){if(!F)continue;if(E[F]){B=E[F],h=F;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)M0.success(`Configuration loaded from package.json: ${h}`);return{config:bW(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)M0.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:NA($,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 xw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return yA.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);yA.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$(Iw(),".config",$),a$(Iw(),".config"),Iw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function NA($,w,A=!1){let J=new OY,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=cA.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}var yA,RY,Oz,Xz=($)=>$,Dz=($,w)=>{for(var A in w)Oz($,A,{get:w[A],enumerable:!0,configurable:!0,set:_z.bind(w,A)})},kz=($,w)=>()=>($&&(w=$($=0)),w),EW,qW,Qw,C1,NW,f9,Z9,tZ,KA,hY,K$,d,W9,pZ,E9,rZ,B9,h9,AY,F9,aZ,sZ,JY,j9,z9,H9,T9,MA,RW,G9,M$,q9,N9,oZ,IA,FY,W$,D,R9,eZ,K9,$W,M9,I9,UY,C9,wW,AW,y9,YY,L9,S9,V9,O9,X9,CA,KW,_9,D9="0.15.6",n$,QA,M1,jY,zY,xA,HY,TY,I1,GY,qY,t0,MW,IW,f0,L0,CW,yW,k9,x9,LW,PA,e6,G$,x,$N,b9,wN,i9,AN,JN,JW,UN,c9,u9,YN,UW,fN,ZN,WN,EN,BN,fY,v9,hN,Z0,VW,bA,OW,XW,VY,_W,DW,iA,kW,QW,xw,r9,M0,TN,GN,qN;var XY=X$(()=>{yA=new YW,RY=new fW,Oz=Object.defineProperty;EW={};Dz(EW,{withErrorRecovery:()=>FW,tryLoadConfig:()=>A9,loadConfigWithResult:()=>$9,loadConfig:()=>GW,isRetryableError:()=>pz,isConfigNotFoundError:()=>tz,isBunfigError:()=>jW,globalPerformanceMonitor:()=>C1,globalCache:()=>Qw,getEnvOrDefault:()=>rz,generateConfigTypes:()=>J9,defaultGeneratedDir:()=>yW,defaultConfigDir:()=>CW,deepMergeWithArrayStrategy:()=>yY,deepMerge:()=>zW,createLibraryConfig:()=>U9,config:()=>w9,bunfigPlugin:()=>Y9,applyEnvVarsToConfig:()=>R1,TypeGenerationError:()=>TY,SchemaValidationError:()=>I1,PluginError:()=>qY,PerformanceMonitor:()=>MY,FileSystemError:()=>HY,ErrorFactory:()=>t0,EnvVarError:()=>xA,EnvProcessor:()=>uA,ConfigValidator:()=>LY,ConfigValidationError:()=>jY,ConfigNotFoundError:()=>QA,ConfigMergeError:()=>zY,ConfigLoader:()=>SY,ConfigLoadError:()=>M1,ConfigFileLoader:()=>vA,ConfigCache:()=>KY,CacheUtils:()=>NW,BunfigError:()=>n$,BrowserConfigError:()=>GY,ArrayMergeStrategies:()=>MW});k9=kz(async()=>{qW=import.meta.require,Qw=new KY,C1=new MY,NW={createKey:Qz,isEquivalent:xz,estimateMemoryUsage:Pz},f9=VA(EY.cwd(),"config"),Z9=VA(EY.cwd(),"src/generated"),tZ=SA.env.CLARITY_LOG_DIR||aj(cz(),"logs"),KA={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},hY=await uz(),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"},d=K$,W9=K$.red,pZ=K$.green,E9=K$.yellow,rZ=K$.blue,B9=K$.magenta,h9=K$.cyan,AY=K$.white,F9=K$.gray,aZ=K$.bgRed,sZ=K$.bgYellow,JY=K$.bold,j9=K$.dim,z9=K$.italic,H9=K$.underline,T9=K$.reset,MA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RW={debug:"\uD83D\uDD0D",info:rZ("ℹ"),success:pZ("✓"),warning:sZ(AY(JY(" WARN "))),error:aZ(AY(JY(" ERROR ")))},G9=new _A("stacks"),M$=new _A("bunfig",{showTags:!0}),q9=_$(K1.cwd(),"config"),N9=_$(K1.cwd(),"src/generated"),oZ=LA.env.CLARITY_LOG_DIR||pj(dz(),"logs"),IA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},FY=await gz(),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$,R9=W$.red,eZ=W$.green,K9=W$.yellow,$W=W$.blue,M9=W$.magenta,I9=W$.cyan,UY=W$.white,C9=W$.gray,wW=W$.bgRed,AW=W$.bgYellow,y9=W$.bgGray,YY=W$.bold,L9=W$.dim,S9=W$.italic,V9=W$.underline,O9=W$.strikethrough,X9=W$.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},KW={debug:"\uD83D\uDD0D",info:$W("ℹ"),success:eZ("✓"),warning:AW(UY(YY(" WARN "))),error:wW(UY(YY(" ERROR ")))},_9=new kA("stacks"),n$=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}`}},QA=class extends n${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})}},M1=class extends n${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}},jY=class extends n${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},zY=class extends n${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}},xA=class extends n${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})}},HY=class extends n${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}},TY=class extends n${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 n${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})}},GY=class extends n${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})}},qY=class extends n${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 QA($,w,A)},configLoad($,w,A){return new M1($,w,A)},configValidation($,w,A){return new jY($,w,A)},configMerge($,w,A,J){return new zY($,w,A,J)},envVar($,w,A,J){return new xA($,w,A,J)},fileSystem($,w,A){return new HY($,w,A)},typeGeneration($,w,A){return new TY($,w,A)},schemaValidation($,w,A){return new I1($,w,A)},browserConfig($,w,A,J){return new GY($,w,A,J)},plugin($,w,A){return new qY($,w,A)}},MW={replace:"replace",concat:"concat",smart:"smart"},IW=/^https?:\/\//,f0=new kA("bunfig",{showTags:!0}),L0=new SY,CW=D$(fw.cwd(),"config"),yW=D$(fw.cwd(),"src/generated")});x9=OA.env.CLARITY_LOG_DIR||qz(Q9(),"logs"),LW={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:x9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PA={...LW},e6=(async()=>{try{let{loadConfig:$}=await k9().then(()=>EW),w=await $({name:"clarity",alias:"logging",defaultConfig:LW,cwd:OA.cwd()});if(w)Object.assign(PA,w)}catch{}return PA})();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"},x=G$,$N=G$.red,b9=G$.green,wN=G$.yellow,i9=G$.blue,AN=G$.magenta,JN=G$.cyan,JW=G$.white,UN=G$.gray,c9=G$.bgRed,u9=G$.bgYellow,YN=G$.bgGray,UW=G$.bold,fN=G$.dim,ZN=G$.italic,WN=G$.underline,EN=G$.strikethrough,BN=G$.reset,fY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},v9={debug:"\uD83D\uDD0D",info:i9("ℹ"),success:b9("✓"),warning:u9(JW(UW(" WARN "))),error:c9(JW(UW(" ERROR ")))};hN=new nA("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}${$}`}};VW=class VW 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})}};bA=class bA 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}};OW=class OW extends Z0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};XW=class XW 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}};VY=class VY 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})}};_W=class _W 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}};DW=class DW 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}};iA=class iA 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})}};kW=class kW 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})}};QW=class QW 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}};xw={configNotFound($,w,A){return new VW($,w,A)},configLoad($,w,A){return new bA($,w,A)},configValidation($,w,A){return new OW($,w,A)},configMerge($,w,A,J){return new XW($,w,A,J)},envVar($,w,A,J){return new VY($,w,A,J)},fileSystem($,w,A){return new _W($,w,A)},typeGeneration($,w,A){return new DW($,w,A)},schemaValidation($,w,A){return new iA($,w,A)},browserConfig($,w,A,J){return new kW($,w,A,J)},plugin($,w,A){return new QW($,w,A)}};r9=/^https?:\/\//;M0=new nA("bunfig",{showTags:!0});TN=new uW;GN=a$(cA.cwd(),"config"),qN=a$(cA.cwd(),"src/generated")});var R;var p0=X$(()=>{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 e9}from"node:module";import kY from"node:os";import QY from"node:path";import{existsSync as vW,statSync as nW}from"fs";import{existsSync as $H,mkdirSync as DN,readdirSync as kN,readFileSync as wH,writeFileSync as QN}from"fs";import{homedir as bw}from"os";import{dirname as bN,resolve as e$}from"path";import CJ from"process";import{existsSync as mW,statSync as dW}from"fs";import{existsSync as $8,mkdirSync as AH,readdirSync as JH,writeFileSync as UH}from"fs";import{homedir as iw}from"os";import{dirname as gW,resolve as Q$}from"path";import Zw from"process";import{join as YH,relative as fH,resolve as lW}from"path";import WJ from"process";import{existsSync as kE,mkdirSync as tN,readdirSync as pN,writeFileSync as rN}from"fs";import{homedir as xY}from"os";import{dirname as oN,resolve as k$}from"path";import V1 from"process";import{join as ZH,relative as WH,resolve as tW}from"path";import EJ from"process";import{existsSync as QE,mkdirSync as JR,readdirSync as UR,writeFileSync as YR}from"fs";import{dirname as ZR,resolve as BJ}from"path";import w8 from"process";import{Buffer as r0}from"buffer";import{createCipheriv as EH,createDecipheriv as BH,randomBytes as PY}from"crypto";import{closeSync as bY,createReadStream as pW,createWriteStream as hH,existsSync as iY,fsyncSync as rW,openSync as aW,writeFileSync as FH}from"fs";import{access as jH,constants as sW,mkdir as zH,readdir as mA,rename as oW,stat as cw,unlink as dA,writeFile as cY}from"fs/promises";import{join as uw}from"path";import I$ from"process";import{pipeline as HH}from"stream/promises";import{createGzip as eW}from"zlib";import vw from"process";import X0 from"process";import{Buffer as S0}from"buffer";import{createCipheriv as TH,createDecipheriv as GH,randomBytes as uY}from"crypto";import{closeSync as vY,createReadStream as $E,createWriteStream as qH,existsSync as gA,fsyncSync as wE,openSync as AE,writeFileSync as NH}from"fs";import{access as RH,constants as JE,mkdir as KH,readdir as lA,rename as UE,stat as nw,unlink as tA,writeFile as nY}from"fs/promises";import{isAbsolute as MH,join as mw,resolve as IH}from"path";import u from"process";import{pipeline as CH}from"stream/promises";import{createGzip as YE}from"zlib";import dw from"process";import _0 from"process";import pA from"process";import{existsSync as rA}from"fs";import{resolve as mY}from"path";import{existsSync as yH}from"fs";import{existsSync as LH,readdirSync as SH}from"fs";import{extname as dY,resolve as fE}from"path";import VH from"process";import{join as OH,relative as XH,resolve as ZE}from"path";import hJ from"process";import{Buffer as V0}from"buffer";import{createCipheriv as _H,createDecipheriv as DH,randomBytes as gY}from"crypto";import{closeSync as lY,createReadStream as WE,createWriteStream as kH,existsSync as aA,fsyncSync as EE,openSync as BE,writeFileSync as QH}from"fs";import{access as xH,constants as hE,mkdir as PH,readdir as sA,rename as FE,stat as gw,unlink as oA,writeFile as tY}from"fs/promises";import{isAbsolute as bH,join as lw,resolve as iH}from"path";import v from"process";import{pipeline as cH}from"stream/promises";import{createGzip as jE}from"zlib";import tw from"process";import D0 from"process";import eA from"process";import{existsSync as $J}from"fs";import{resolve as pY}from"path";import{existsSync as uH}from"fs";import{exec as WG}from"node:child_process";import SE from"node:fs";import EG from"node:os";import W0 from"node:path";import TB from"node:process";import{promisify as BG}from"node:util";import sw from"node:crypto";import k0 from"node:fs";import z8 from"node:path";import{execSync as DE}from"node:child_process";import IJ from"node:os";class xE{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(!vW($))return!0;return nW($).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=vW(A)?nW(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 PE{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 mH($,w){this[$]=nH.bind(null,w)}class T8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,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(!mW($))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 U=mW(A)?dW(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 G8{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 lH($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function tH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function pH($){return $.getStats().size*2}function q8($,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((Y)=>r(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((Y)=>r(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>jJ(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]=q8(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((W)=>r(W)&&("name"in W)&&W.name===f.name))Y.push(f)}else if(r(f)&&"path"in f){if(!Y.find((W)=>r(W)&&("path"in W)&&W.path===f.path))Y.push(f)}else if(!Y.some((W)=>jJ(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 jJ($,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(!jJ($[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(!jJ($[U],w[U]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function rH($,w){if(!QE($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return q8(w,J)}catch{return null}}catch{return null}}async function aH({name:$="",cwd:w,defaultConfig:A}){let J=w||w8.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=BJ(J,`${f}${W}`),E=await rH(Z,A);if(E!==null)return E}try{let f=BJ(J,"package.json");if(QE(f)){let W=(await import(f))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return q8(A,W)}catch{}}}catch{}return A}function sH($,w={}){let A=EJ.cwd();while(A.includes("storage"))A=tW(A,"..");let J=tW(A,$||"");if(w?.relative)return WH(EJ.cwd(),J);return J}async function oH(){try{let $=await aH({name:"clarity",defaultConfig:UJ,cwd:EJ.cwd(),endpoint:"",headers:{}});return{...UJ,...$}}catch{return UJ}}function $$(){if(X0.env.NODE_ENV==="test"||X0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function eH(){if(X0.env.NODE_ENV==="test"||X0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X0<"u"){let $=X0.type;if($==="renderer"||$==="worker")return!1;return!!(X0.versions&&(X0.versions.node||X0.versions.bun))}return!1}class iE{async format($){let w=await 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:vw.pid,hostname:w(),environment:vw.env.NODE_ENV||"development",platform:vw.platform,version:vw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vw.env.NODE_ENV||vw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zJ{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={...J8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new iE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??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 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{...YJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...YJ};return{...YJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:J8.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 jH(this.config.logDirectory,sW.F_OK|sW.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await zH(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:r0.from($);try{if(!iY(this.currentLogFile))await cY(this.currentLogFile,"",{mode:420});if(J=aW(this.currentLogFile,"a",420),FH(J,W,{flag:"a"}),rW(J),J!==void 0)bY(J),J=void 0;if((await cw(this.currentLogFile)).size===0){if(await cY(this.currentLogFile,W,{flag:"w",mode:420}),(await cw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let B=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,B);let h=f*2**U;await new Promise((j)=>setTimeout(j,h)),U++;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{bY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let E=W,B=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),W}U++;let Z=f*2**(U-1);await new Promise((E)=>setTimeout(E,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 uw(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 uw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return uw(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 $=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 PY(16).toString("hex")}generateKey(){return PY(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=PY(16),J=EH("aes-256-gcm",w,A),U=r0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:r0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=eW(),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($$())return;let $=await cw(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 mA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await cw(A).catch(()=>null))try{if(await oW(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await dA(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 cY(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 cw(A).catch(()=>null))await oW(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await mA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await dA(uw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=pW($),J=hH(w),U=eW();await HH(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()})),iY(this.currentLogFile))try{let $=aW(this.currentLogFile,"r+");rW($),bY($)}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 $=(await mA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await dA(uw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=I$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${g.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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 E=pE[$],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",h;switch($){case"debug":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:g.gray(f),level:$}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:g.green(f),level:$}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h),W){let j=W.split(`
|
|
63
|
+
`;return A}}function d9($,w,A={}){return xW($,w,A,new WeakMap)}function xW($,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 PW($,w,U,J);if(!o$(w)||!o$($))return w;return p9($,w,A,J)}function PW($,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 g9($,w);case"smart":return l9($,w,J);default:return w}return w}function g9($,w){let A=[...w];for(let J of $)if(!A.some((U)=>NY(U,J)))A.push(J);return A}function l9($,w,A){if(w.length===0)return $;if($.length===0)return w;if(o$(w[0])&&o$($[0]))return t9($,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 t9($,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((E)=>o$(E)&&(W in E)&&E[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function p9($,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]=xW(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=PW(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function bW($,w,A="replace"){return d9($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function NY($,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(!NY($[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(!NY($[U],w[U]))return!1}return!0}return!1}function o$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class iW{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 E=yA.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!qA($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new bA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new bA($,Error("Configuration must export a valid object"),"unknown");let G={config:bW(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)yA.setWithFileCheck("file",G,$,Y);return G}catch(E){throw E instanceof Error?xw.configLoad($,E):xw.configLoad($,Error(String(E)))}};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(ZY(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 m9(async()=>{return qA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!qA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=ZY($,`${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=ZY($,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(!qA($))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 cW{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await RY.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!r9(w))throw new iA(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 iA(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:a9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function s9($){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 uW{fileLoader=new iW;envProcessor=new OY;validator=new cW;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)M0.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 M0.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:E="replace",verbose:B=!1}=$,h=Y||cA.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(a$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw xw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),warnings:[`No configuration file found for "${J}"${s9(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let E=W?NA($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)M0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)M0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?NA($,A,U):A,W=[a$(Iw(),".config",$),a$(Iw(),".config"),Iw()];for(let Z of W){if(U)M0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)M0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?NA($,J,Y):J;try{let Z=a$(A,"package.json");if(!dj(Z))return null;let E={};try{E=JSON.parse(gj(Z,"utf8"))}catch(j){if(Y)M0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let B=E[$],h=$;if(!B&&w){let j=Array.isArray(w)?w:[w];for(let F of j){if(!F)continue;if(E[F]){B=E[F],h=F;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)M0.success(`Configuration loaded from package.json: ${h}`);return{config:bW(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)M0.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:NA($,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 xw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return yA.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);yA.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$(Iw(),".config",$),a$(Iw(),".config"),Iw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function NA($,w,A=!1){let J=new OY,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=cA.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}var yA,RY,Xz,_z=($)=>$,kz=($,w)=>{for(var A in w)Xz($,A,{get:w[A],enumerable:!0,configurable:!0,set:Dz.bind(w,A)})},Qz=($,w)=>()=>($&&(w=$($=0)),w),EW,qW,Qw,C1,NW,Z9,W9,tZ,KA,hY,K$,d,E9,pZ,B9,rZ,h9,F9,AY,j9,aZ,sZ,JY,z9,H9,T9,G9,MA,RW,q9,M$,N9,R9,oZ,IA,FY,W$,D,K9,eZ,M9,$W,I9,C9,UY,y9,wW,AW,L9,YY,S9,V9,O9,X9,_9,CA,KW,D9,k9="0.15.6",m$,QA,M1,jY,zY,xA,HY,TY,I1,GY,qY,t0,MW,IW,f0,L0,CW,yW,Q9,P9,LW,PA,JN,G$,x,UN,i9,YN,c9,fN,ZN,JW,WN,u9,v9,EN,UW,BN,hN,FN,jN,zN,fY,n9,HN,Z0,VW,bA,OW,XW,VY,_W,DW,iA,kW,QW,xw,a9,M0,RN,KN,MN;var XY=X$(()=>{yA=new YW,RY=new fW,Xz=Object.defineProperty;EW={};kz(EW,{withErrorRecovery:()=>FW,tryLoadConfig:()=>J9,loadConfigWithResult:()=>w9,loadConfig:()=>GW,isRetryableError:()=>rz,isConfigNotFoundError:()=>pz,isBunfigError:()=>jW,globalPerformanceMonitor:()=>C1,globalCache:()=>Qw,getEnvOrDefault:()=>az,generateConfigTypes:()=>U9,defaultGeneratedDir:()=>yW,defaultConfigDir:()=>CW,deepMergeWithArrayStrategy:()=>yY,deepMerge:()=>zW,createLibraryConfig:()=>Y9,config:()=>A9,bunfigPlugin:()=>f9,applyEnvVarsToConfig:()=>R1,TypeGenerationError:()=>TY,SchemaValidationError:()=>I1,PluginError:()=>qY,PerformanceMonitor:()=>MY,FileSystemError:()=>HY,ErrorFactory:()=>t0,EnvVarError:()=>xA,EnvProcessor:()=>uA,ConfigValidator:()=>LY,ConfigValidationError:()=>jY,ConfigNotFoundError:()=>QA,ConfigMergeError:()=>zY,ConfigLoader:()=>SY,ConfigLoadError:()=>M1,ConfigFileLoader:()=>vA,ConfigCache:()=>KY,CacheUtils:()=>NW,BunfigError:()=>m$,BrowserConfigError:()=>GY,ArrayMergeStrategies:()=>MW});Q9=Qz(async()=>{qW=import.meta.require,Qw=new KY,C1=new MY,NW={createKey:xz,isEquivalent:Pz,estimateMemoryUsage:bz},Z9=VA(EY.cwd(),"config"),W9=VA(EY.cwd(),"src/generated"),tZ=SA.env.CLARITY_LOG_DIR||sj(uz(),"logs"),KA={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},hY=await vz(),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"},d=K$,E9=K$.red,pZ=K$.green,B9=K$.yellow,rZ=K$.blue,h9=K$.magenta,F9=K$.cyan,AY=K$.white,j9=K$.gray,aZ=K$.bgRed,sZ=K$.bgYellow,JY=K$.bold,z9=K$.dim,H9=K$.italic,T9=K$.underline,G9=K$.reset,MA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RW={debug:"\uD83D\uDD0D",info:rZ("ℹ"),success:pZ("✓"),warning:sZ(AY(JY(" WARN "))),error:aZ(AY(JY(" ERROR ")))},q9=new _A("stacks"),M$=new _A("bunfig",{showTags:!0}),N9=_$(K1.cwd(),"config"),R9=_$(K1.cwd(),"src/generated"),oZ=LA.env.CLARITY_LOG_DIR||rj(gz(),"logs"),IA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oZ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},FY=await lz(),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$,K9=W$.red,eZ=W$.green,M9=W$.yellow,$W=W$.blue,I9=W$.magenta,C9=W$.cyan,UY=W$.white,y9=W$.gray,wW=W$.bgRed,AW=W$.bgYellow,L9=W$.bgGray,YY=W$.bold,S9=W$.dim,V9=W$.italic,O9=W$.underline,X9=W$.strikethrough,_9=W$.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},KW={debug:"\uD83D\uDD0D",info:$W("ℹ"),success:eZ("✓"),warning:AW(UY(YY(" WARN "))),error:wW(UY(YY(" ERROR ")))},D9=new kA("stacks"),m$=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}`}},QA=class extends m${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})}},M1=class extends m${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}},jY=class extends m${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},zY=class extends m${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}},xA=class extends m${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})}},HY=class extends m${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}},TY=class extends m${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 m${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})}},GY=class extends m${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})}},qY=class extends m${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 QA($,w,A)},configLoad($,w,A){return new M1($,w,A)},configValidation($,w,A){return new jY($,w,A)},configMerge($,w,A,J){return new zY($,w,A,J)},envVar($,w,A,J){return new xA($,w,A,J)},fileSystem($,w,A){return new HY($,w,A)},typeGeneration($,w,A){return new TY($,w,A)},schemaValidation($,w,A){return new I1($,w,A)},browserConfig($,w,A,J){return new GY($,w,A,J)},plugin($,w,A){return new qY($,w,A)}},MW={replace:"replace",concat:"concat",smart:"smart"},IW=/^https?:\/\//,f0=new kA("bunfig",{showTags:!0}),L0=new SY,CW=D$(fw.cwd(),"config"),yW=D$(fw.cwd(),"src/generated")});P9=OA.env.CLARITY_LOG_DIR||Nz(x9(),"logs"),LW={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:P9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PA={...LW},JN=(async()=>{try{let{loadConfig:$}=await Q9().then(()=>EW),w=await $({name:"clarity",alias:"logging",defaultConfig:LW,cwd:OA.cwd()});if(w)Object.assign(PA,w)}catch{}return PA})();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"},x=G$,UN=G$.red,i9=G$.green,YN=G$.yellow,c9=G$.blue,fN=G$.magenta,ZN=G$.cyan,JW=G$.white,WN=G$.gray,u9=G$.bgRed,v9=G$.bgYellow,EN=G$.bgGray,UW=G$.bold,BN=G$.dim,hN=G$.italic,FN=G$.underline,jN=G$.strikethrough,zN=G$.reset,fY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},n9={debug:"\uD83D\uDD0D",info:c9("ℹ"),success:i9("✓"),warning:v9(JW(UW(" WARN "))),error:u9(JW(UW(" ERROR ")))};HN=new nA("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}${$}`}};VW=class VW 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})}};bA=class bA 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}};OW=class OW extends Z0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};XW=class XW 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}};VY=class VY 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})}};_W=class _W 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}};DW=class DW 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}};iA=class iA 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})}};kW=class kW 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})}};QW=class QW 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}};xw={configNotFound($,w,A){return new VW($,w,A)},configLoad($,w,A){return new bA($,w,A)},configValidation($,w,A){return new OW($,w,A)},configMerge($,w,A,J){return new XW($,w,A,J)},envVar($,w,A,J){return new VY($,w,A,J)},fileSystem($,w,A){return new _W($,w,A)},typeGeneration($,w,A){return new DW($,w,A)},schemaValidation($,w,A){return new iA($,w,A)},browserConfig($,w,A,J){return new kW($,w,A,J)},plugin($,w,A){return new QW($,w,A)}};a9=/^https?:\/\//;M0=new nA("bunfig",{showTags:!0});RN=new uW;KN=a$(cA.cwd(),"config"),MN=a$(cA.cwd(),"src/generated")});var R;var p0=X$(()=>{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 $H}from"node:module";import kY from"node:os";import QY from"node:path";import{existsSync as vW,statSync as nW}from"fs";import{existsSync as wH,mkdirSync as PN,readdirSync as bN,readFileSync as AH,writeFileSync as iN}from"fs";import{homedir as bw}from"os";import{dirname as vN,resolve as e$}from"path";import CJ from"process";import{existsSync as mW,statSync as dW}from"fs";import{existsSync as $8,mkdirSync as JH,readdirSync as UH,writeFileSync as YH}from"fs";import{homedir as iw}from"os";import{dirname as gW,resolve as Q$}from"path";import Zw from"process";import{join as fH,relative as ZH,resolve as lW}from"path";import WJ from"process";import{existsSync as kE,mkdirSync as sN,readdirSync as oN,writeFileSync as eN}from"fs";import{homedir as xY}from"os";import{dirname as AR,resolve as k$}from"path";import V1 from"process";import{join as WH,relative as EH,resolve as tW}from"path";import EJ from"process";import{existsSync as QE,mkdirSync as ZR,readdirSync as WR,writeFileSync as ER}from"fs";import{dirname as hR,resolve as BJ}from"path";import w8 from"process";import{Buffer as r0}from"buffer";import{createCipheriv as BH,createDecipheriv as hH,randomBytes as PY}from"crypto";import{closeSync as bY,createReadStream as pW,createWriteStream as FH,existsSync as iY,fsyncSync as rW,openSync as aW,writeFileSync as jH}from"fs";import{access as zH,constants as sW,mkdir as HH,readdir as mA,rename as oW,stat as cw,unlink as dA,writeFile as cY}from"fs/promises";import{join as uw}from"path";import I$ from"process";import{pipeline as TH}from"stream/promises";import{createGzip as eW}from"zlib";import vw from"process";import X0 from"process";import{Buffer as S0}from"buffer";import{createCipheriv as GH,createDecipheriv as qH,randomBytes as uY}from"crypto";import{closeSync as vY,createReadStream as $E,createWriteStream as NH,existsSync as gA,fsyncSync as wE,openSync as AE,writeFileSync as RH}from"fs";import{access as KH,constants as JE,mkdir as MH,readdir as lA,rename as UE,stat as nw,unlink as tA,writeFile as nY}from"fs/promises";import{isAbsolute as IH,join as mw,resolve as CH}from"path";import u from"process";import{pipeline as yH}from"stream/promises";import{createGzip as YE}from"zlib";import dw from"process";import _0 from"process";import pA from"process";import{existsSync as rA}from"fs";import{resolve as mY}from"path";import{existsSync as LH}from"fs";import{existsSync as SH,readdirSync as VH}from"fs";import{extname as dY,resolve as fE}from"path";import OH from"process";import{join as XH,relative as _H,resolve as ZE}from"path";import hJ from"process";import{Buffer as V0}from"buffer";import{createCipheriv as DH,createDecipheriv as kH,randomBytes as gY}from"crypto";import{closeSync as lY,createReadStream as WE,createWriteStream as QH,existsSync as aA,fsyncSync as EE,openSync as BE,writeFileSync as xH}from"fs";import{access as PH,constants as hE,mkdir as bH,readdir as sA,rename as FE,stat as gw,unlink as oA,writeFile as tY}from"fs/promises";import{isAbsolute as iH,join as lw,resolve as cH}from"path";import v from"process";import{pipeline as uH}from"stream/promises";import{createGzip as jE}from"zlib";import tw from"process";import D0 from"process";import eA from"process";import{existsSync as $J}from"fs";import{resolve as pY}from"path";import{existsSync as vH}from"fs";import{exec as EG}from"node:child_process";import SE from"node:fs";import BG from"node:os";import W0 from"node:path";import TB from"node:process";import{promisify as hG}from"node:util";import sw from"node:crypto";import k0 from"node:fs";import z8 from"node:path";import{execSync as DE}from"node:child_process";import IJ from"node:os";class xE{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(!vW($))return!0;return nW($).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=vW(A)?nW(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 PE{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 dH($,w){this[$]=mH.bind(null,w)}class T8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,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(!mW($))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 U=mW(A)?dW(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 G8{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 tH($,w={}){let A=Object.keys(w).sort().map((J)=>`${J}:${w[J]}`).join("|");return A?`${$}:${A}`:$}function pH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function rH($){return $.getStats().size*2}function q8($,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((Y)=>r(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((Y)=>r(Y)&&("path"in Y)&&Y.path===U.path))J.push(U)}else if(!J.some((Y)=>jJ(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]=q8(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((W)=>r(W)&&("name"in W)&&W.name===f.name))Y.push(f)}else if(r(f)&&"path"in f){if(!Y.find((W)=>r(W)&&("path"in W)&&W.path===f.path))Y.push(f)}else if(!Y.some((W)=>jJ(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 jJ($,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(!jJ($[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(!jJ($[U],w[U]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function aH($,w){if(!QE($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return q8(w,J)}catch{return null}}catch{return null}}async function sH({name:$="",cwd:w,defaultConfig:A}){let J=w||w8.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=BJ(J,`${f}${W}`),E=await aH(Z,A);if(E!==null)return E}try{let f=BJ(J,"package.json");if(QE(f)){let W=(await import(f))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return q8(A,W)}catch{}}}catch{}return A}function oH($,w={}){let A=EJ.cwd();while(A.includes("storage"))A=tW(A,"..");let J=tW(A,$||"");if(w?.relative)return EH(EJ.cwd(),J);return J}async function eH(){try{let $=await sH({name:"clarity",defaultConfig:UJ,cwd:EJ.cwd(),endpoint:"",headers:{}});return{...UJ,...$}}catch{return UJ}}function $$(){if(X0.env.NODE_ENV==="test"||X0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $T(){if(X0.env.NODE_ENV==="test"||X0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X0<"u"){let $=X0.type;if($==="renderer"||$==="worker")return!1;return!!(X0.versions&&(X0.versions.node||X0.versions.bun))}return!1}class iE{async format($){let w=await $T(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:vw.pid,hostname:w(),environment:vw.env.NODE_ENV||"development",platform:vw.platform,version:vw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:vw.env.NODE_ENV||vw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zJ{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={...J8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new iE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??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 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{...YJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...YJ};return{...YJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:J8.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 zH(this.config.logDirectory,sW.F_OK|sW.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await HH(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:r0.from($);try{if(!iY(this.currentLogFile))await cY(this.currentLogFile,"",{mode:420});if(J=aW(this.currentLogFile,"a",420),jH(J,W,{flag:"a"}),rW(J),J!==void 0)bY(J),J=void 0;if((await cw(this.currentLogFile)).size===0){if(await cY(this.currentLogFile,W,{flag:"w",mode:420}),(await cw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let B=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,B);let h=f*2**U;await new Promise((j)=>setTimeout(j,h)),U++;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{bY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let E=W,B=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),W}U++;let Z=f*2**(U-1);await new Promise((E)=>setTimeout(E,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 uw(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 uw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return uw(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 $=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 PY(16).toString("hex")}generateKey(){return PY(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=PY(16),J=BH("aes-256-gcm",w,A),U=r0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:r0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=eW(),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($$())return;let $=await cw(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 mA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await cw(A).catch(()=>null))try{if(await oW(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await dA(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 cY(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 cw(A).catch(()=>null))await oW(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await mA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await dA(uw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=pW($),J=FH(w),U=eW();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);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()})),iY(this.currentLogFile))try{let $=aW(this.currentLogFile,"r+");rW($),bY($)}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 $=(await mA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await dA(uw(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=I$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${g.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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 E=pE[$],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",h;switch($){case"debug":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:g.gray(f),level:$}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:g.green(f),level:$}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h),W){let j=W.split(`
|
|
64
64
|
`);for(let F of j)if(F.trim()&&!F.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:g.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!$$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}if(!this.shouldLog($))return;let Z=`${Y} ${this.environment}.${$.toUpperCase()}: ${f}
|
|
65
65
|
`;if(W)Z+=`${W}
|
|
66
66
|
`;Z=Z.replace(this.ANSI_PATTERN,""),await this.writeToFile(Z)}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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),Z=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)Z+=` ${JSON.stringify(A)}`;if(Z+=`
|
|
67
|
-
`,Z=Z.replace(this.ANSI_PATTERN,""),this.fancy&&!$$()){let E=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:g.green("✓"),tag:E,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!$$())console.error(Z.trim());await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new zJ(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(!iY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pW(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=r0.isBuffer($)?$:r0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W=
|
|
67
|
+
`,Z=Z.replace(this.ANSI_PATTERN,""),this.fancy&&!$$()){let E=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:g.green("✓"),tag:E,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!$$())console.error(Z.trim());await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new zJ(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(!iY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pW(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=r0.isBuffer($)?$:r0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W=hH("aes-256-gcm",A,U);return W.setAuthTag(Y),r0.concat([W.update(f),W.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return $$()}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 Y=$.split(`
|
|
68
68
|
`),f=Math.max(...Y.map((B)=>B.length))+2,W=`┌${"─".repeat(f)}┐`,Z=`└${"─".repeat(f)}┘`,E=Y.map((B)=>{let h=" ".repeat(f-B.length-2);return`│ ${B}${h} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:g.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(W)})),E.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:g.cyan(Z),showTimestamp:!1}))}else if(!$$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let U=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
69
69
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if($$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=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(U==="y"||U==="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 U=/%([sdijfo%])/g,Y=0;if(A=$.replace(U,(f,W)=>{if(W==="%")return"%";if(Y>=w.length)return f;let Z=w[Y++];switch(W){case"s":return String(Z);case"d":case"i":return Number(Z).toString();case"j":case"o":return JSON.stringify(Z,null,2);default:return f}}),Y<w.length)A+=` ${w.slice(Y).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!$$()){let U=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Y=g.blue("◐");console.error(`${Y} ${U} ${g.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
70
70
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}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:(J,U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),U!==void 0)this.activeProgressBar.message=U;let Y=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Y)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())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,U="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||$$())return;I$.stdout.write(`${"\r".padEnd(I$.stdout.columns||80)}\r`),this.log(U,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||$$()||!I$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=g.green("━".repeat(J)),f=g.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=w||A===100?g.green("✓"):g.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=I$.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,I$.stdout.write($.lastRenderedLine),w)I$.stdout.write(`
|
|
71
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!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($$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await mA(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=uw(this.config.logDirectory,J);if($.before)try{if((await cw(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 dA(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 JJ($,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 U of $)if(n(U)&&"name"in U){if(!J.find((Y)=>n(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(n(U)&&"path"in U){if(!J.find((Y)=>n(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(!n(w)||!n($))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(n(U)&&n(A[J]))A[J]=JJ(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&n(U[0])&&n(A[J][0])){let Y=[...U];for(let f of A[J])if(n(f)&&"name"in f){if(!Y.find((W)=>n(W)&&("name"in W)&&W.name===f.name))Y.push(f)}else if(n(f)&&"path"in f){if(!Y.find((W)=>n(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 N8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:JJ($,w);if(Array.isArray($))return A==="replace"?w:JJ($,w);if(!n(w)||!n($))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]=JJ(f,Y);else if(n(Y)&&n(f))J[U]=N8(f,Y,A);else J[U]=Y}return J}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(n($)&&n(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 n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function wJ($,w,A="replace"){if(!kE($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return N8(w,U,A)}catch{return null}}catch{return null}}function $T($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${J}_${h.map(j).join("_")}`,T=`${J}_${h.map((H)=>H.toUpperCase()).join("_")}`;if(A)y$.info(`Checking environment variable ${F} for config ${$}.${h.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))Z[E]=Y(B,h);else{let H=V1.env[F]||V1.env[T];if(H!==void 0){if(A)y$.info(`Using environment variable ${H?F:T} for config ${$}.${h.join(".")}`);if(typeof B==="number")Z[E]=Number(H);else if(typeof B==="boolean")Z[E]=H.toLowerCase()==="true";else if(Array.isArray(B))try{let G=JSON.parse(H);if(Array.isArray(G))Z[E]=G;else Z[E]=H.split(",").map((q)=>q.trim())}catch{Z[E]=H.split(",").map((G)=>G.trim())}else Z[E]=H}}}return Z}return Y(U)}async function wT({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)?$T($,U,Y):U,E=A||V1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(Y)y$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let h=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,k$(E,"config"),k$(E,".config"),J?k$(E,J):void 0].filter(Boolean)));for(let G of H){if(Y)y$.info(`Searching for configuration in: ${G}`);let q=[k$(E,"config"),k$(E,".config")].concat(J?[k$(E,J)]:[]).includes(G)?[...h,...j,...F,...T]:[...j,...h,...T,...F];for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from: ${C}`);return y}}}if($){let G=k$(xY(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)y$.info(`Checking user config directory: ${G}`);for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from user config directory: ${C}`);return y}}}if($){let G=k$(xY(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)y$.info(`Checking user config directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from user config directory dotfile: ${C}`);return y}}}if($){let G=xY(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)y$.info(`Checking user home directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from user home directory: ${C}`);return y}}}try{let G=k$(E,"package.json");if(kE(G)){let q=await import(G),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 N8(Z,N,W)}catch(K){if(Y)y$.warn("Failed to merge package.json config:",K)}}}catch(G){if(Y)y$.warn("Failed to load package.json:",G)}if(Y)y$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function AT($,w={}){let A=WJ.cwd();while(A.includes("storage"))A=lW(A,"..");let J=lW(A,$||"");if(w?.relative)return fH(WJ.cwd(),J);return J}async function JT(){try{let $=await wT({name:"clarity",alias:"logging",defaultConfig:fJ,cwd:WJ.cwd()});return{...fJ,...$||{}}}catch{return fJ}}function B$(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UT(){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 cE{async format($){let w=await UT(),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 TJ{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={...U8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new cE,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??u.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{...ZJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZJ};return{...ZJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:U8.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 RH(this.config.logDirectory,JE.F_OK|JE.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await KH(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:S0.from($);try{if(!gA(this.currentLogFile))await nY(this.currentLogFile,"",{mode:420});if(J=AE(this.currentLogFile,"a",420),NH(J,W,{flag:"a"}),wE(J),J!==void 0)vY(J),J=void 0;if((await nw(this.currentLogFile)).size===0){if(await nY(this.currentLogFile,W,{flag:"w",mode:420}),(await nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let B=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,B);let h=f*2**U;await new Promise((j)=>setTimeout(j,h)),U++;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{vY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let E=W,B=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),W}U++;let Z=f*2**(U-1);await new Promise((E)=>setTimeout(E,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 mw(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 mw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return mw(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 uY(16).toString("hex")}generateKey(){return uY(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=uY(16),J=TH("aes-256-gcm",w,A),U=S0.isBuffer($)?$:S0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),E=S0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=YE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(S0.from(S0.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 nw(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 lA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await nw(A).catch(()=>null))try{if(await UE(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 nY(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 nw(A).catch(()=>null))await UE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await lA(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(mw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=$E($),J=qH(w),U=YE();await CH(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()})),gA(this.currentLogFile))try{let $=AE(this.currentLogFile,"r+");wE($),vY($)}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 lA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await tA(mw(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 u.env.NO_COLOR<"u",w=u.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof u.stderr<"u"&&u.stderr.isTTY||typeof u.stdout<"u"&&u.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=u.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${k.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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 $=u.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=u.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(MH(w)||w.startsWith("./")||w.startsWith("../"))w=IH(w);else return null;return gA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":rE[$],j=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:k.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:k.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
71
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||$$()||!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($$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await mA(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=uw(this.config.logDirectory,J);if($.before)try{if((await cw(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 dA(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 JJ($,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 U of $)if(n(U)&&"name"in U){if(!J.find((Y)=>n(Y)&&("name"in Y)&&Y.name===U.name))J.push(U)}else if(n(U)&&"path"in U){if(!J.find((Y)=>n(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(!n(w)||!n($))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(n(U)&&n(A[J]))A[J]=JJ(A[J],U);else if(Array.isArray(U)&&Array.isArray(A[J]))if(U.length>0&&A[J].length>0&&n(U[0])&&n(A[J][0])){let Y=[...U];for(let f of A[J])if(n(f)&&"name"in f){if(!Y.find((W)=>n(W)&&("name"in W)&&W.name===f.name))Y.push(f)}else if(n(f)&&"path"in f){if(!Y.find((W)=>n(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 N8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:JJ($,w);if(Array.isArray($))return A==="replace"?w:JJ($,w);if(!n(w)||!n($))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]=JJ(f,Y);else if(n(Y)&&n(f))J[U]=N8(f,Y,A);else J[U]=Y}return J}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(n($)&&n(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 n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function wJ($,w,A="replace"){if(!kE($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return N8(w,U,A)}catch{return null}}catch{return null}}function wT($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${J}_${h.map(j).join("_")}`,T=`${J}_${h.map((H)=>H.toUpperCase()).join("_")}`;if(A)y$.info(`Checking environment variable ${F} for config ${$}.${h.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))Z[E]=Y(B,h);else{let H=V1.env[F]||V1.env[T];if(H!==void 0){if(A)y$.info(`Using environment variable ${H?F:T} for config ${$}.${h.join(".")}`);if(typeof B==="number")Z[E]=Number(H);else if(typeof B==="boolean")Z[E]=H.toLowerCase()==="true";else if(Array.isArray(B))try{let G=JSON.parse(H);if(Array.isArray(G))Z[E]=G;else Z[E]=H.split(",").map((q)=>q.trim())}catch{Z[E]=H.split(",").map((G)=>G.trim())}else Z[E]=H}}}return Z}return Y(U)}async function AT({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)?wT($,U,Y):U,E=A||V1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(Y)y$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let h=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,k$(E,"config"),k$(E,".config"),J?k$(E,J):void 0].filter(Boolean)));for(let G of H){if(Y)y$.info(`Searching for configuration in: ${G}`);let q=[k$(E,"config"),k$(E,".config")].concat(J?[k$(E,J)]:[]).includes(G)?[...h,...j,...F,...T]:[...j,...h,...T,...F];for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from: ${C}`);return y}}}if($){let G=k$(xY(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)y$.info(`Checking user config directory: ${G}`);for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from user config directory: ${C}`);return y}}}if($){let G=k$(xY(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)y$.info(`Checking user config directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from user config directory dotfile: ${C}`);return y}}}if($){let G=xY(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)y$.info(`Checking user home directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=k$(G,`${N}${K}`),y=await wJ(C,Z,W);if(y!==null){if(Y)y$.success(`Configuration loaded from user home directory: ${C}`);return y}}}try{let G=k$(E,"package.json");if(kE(G)){let q=await import(G),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 N8(Z,N,W)}catch(K){if(Y)y$.warn("Failed to merge package.json config:",K)}}}catch(G){if(Y)y$.warn("Failed to load package.json:",G)}if(Y)y$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function JT($,w={}){let A=WJ.cwd();while(A.includes("storage"))A=lW(A,"..");let J=lW(A,$||"");if(w?.relative)return ZH(WJ.cwd(),J);return J}async function UT(){try{let $=await AT({name:"clarity",alias:"logging",defaultConfig:fJ,cwd:WJ.cwd()});return{...fJ,...$||{}}}catch{return fJ}}function B$(){if(_0.env.NODE_ENV==="test"||_0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YT(){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 cE{async format($){let w=await YT(),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 TJ{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={...U8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new cE,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??u.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{...ZJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZJ};return{...ZJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:U8.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 KH(this.config.logDirectory,JE.F_OK|JE.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await MH(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:S0.from($);try{if(!gA(this.currentLogFile))await nY(this.currentLogFile,"",{mode:420});if(J=AE(this.currentLogFile,"a",420),RH(J,W,{flag:"a"}),wE(J),J!==void 0)vY(J),J=void 0;if((await nw(this.currentLogFile)).size===0){if(await nY(this.currentLogFile,W,{flag:"w",mode:420}),(await nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let B=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,B);let h=f*2**U;await new Promise((j)=>setTimeout(j,h)),U++;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{vY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let E=W,B=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),W}U++;let Z=f*2**(U-1);await new Promise((E)=>setTimeout(E,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 mw(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 mw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return mw(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 uY(16).toString("hex")}generateKey(){return uY(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=uY(16),J=GH("aes-256-gcm",w,A),U=S0.isBuffer($)?$:S0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),E=S0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=YE(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(S0.from(S0.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 nw(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 lA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await nw(A).catch(()=>null))try{if(await UE(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 nY(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 nw(A).catch(()=>null))await UE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await lA(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(mw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=$E($),J=NH(w),U=YE();await yH(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()})),gA(this.currentLogFile))try{let $=AE(this.currentLogFile,"r+");wE($),vY($)}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 lA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await tA(mw(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 u.env.NO_COLOR<"u",w=u.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof u.stderr<"u"&&u.stderr.isTTY||typeof u.stdout<"u"&&u.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=u.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${k.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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 $=u.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=u.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(IH(w)||w.startsWith("./")||w.startsWith("../"))w=CH(w);else return null;return gA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":rE[$],j=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:k.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:k.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
72
72
|
`);for(let H of T)if(H.trim()&&!H.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:k.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!B$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}if(!this.shouldLog($))return;let B=`${Y} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
73
73
|
`;if(W)B+=`${W}
|
|
74
74
|
`;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,w=""){let A={update:(U,Y)=>{},finish:(U)=>{},interrupt:(U,Y)=>{}};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$()&&u.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,Y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),Y!==void 0)this.activeProgressBar.message=Y;if(this.shouldStyleConsole()&&!B$()&&u.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,Y="info")=>{if(!B$()&&u.stdout.isTTY)u.stdout.write(`
|
|
75
75
|
`);if(this[Y==="warning"?"warn":Y](U),this.activeProgressBar&&this.shouldStyleConsole()&&!B$()&&u.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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),Z=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)Z+=` ${JSON.stringify(A)}`;if(Z+=`
|
|
76
|
-
`,Z=Z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":k.green("✓"),tag:E,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!B$())console.error(Z.trim());if(this.shouldWriteToFile())await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new TJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(B$())throw Error("createReadStream is not supported in browser environments");if(!gA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $E(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=S0.isBuffer($)?$:S0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=
|
|
76
|
+
`,Z=Z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":k.green("✓"),tag:E,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!B$())console.error(Z.trim());if(this.shouldWriteToFile())await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new TJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(B$())throw Error("createReadStream is not supported in browser environments");if(!gA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $E(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=S0.isBuffer($)?$:S0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=qH("aes-256-gcm",A,U);W.setAuthTag(Y);let Z=W.update(f),E=W.final(),B=Z.length+E.length,h=S0.allocUnsafe(B);return Z.copy(h,0),E.copy(h,Z.length),h.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:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
77
77
|
`),Z=Math.max(...W.map((j)=>j.length))+2,E=`┌${"─".repeat(Z)}┐`,B=`└${"─".repeat(Z)}┘`,h=W.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:k.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(E),showTimestamp:!1})),h.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:k.cyan(B),showTimestamp:!1}))}else if(!B$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
78
78
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(B$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${k.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();u.stdin.removeListener("data",A);try{if(typeof u.stdin.setRawMode==="function")u.stdin.setRawMode(!1)}catch{}u.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof u.stdin.setRawMode==="function")u.stdin.setRawMode(!0)}catch{}u.stdin.resume(),u.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,W=0;if(A=$.replace(f,(Z,E)=>{if(E==="%")return"%";if(W>=w.length)return Z;let B=w[W++];switch(E){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 Z}}),W<w.length)A+=` ${w.slice(W).map((Z)=>typeof Z==="object"?JSON.stringify(Z,null,2):String(Z)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${k.blue("◐")} `;console.error(`${W}${f} ${k.cyan(J)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
79
79
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!u.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=k.green("━".repeat(J)),f=k.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":w||A===100?k.green("✓"):k.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=u.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,u.stdout.write($.lastRenderedLine),w)u.stdout.write(`
|
|
80
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B$()||!u.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 lA(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=mw(this.config.logDirectory,J);if($.before)try{if((await nw(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 tA(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)}}}async function uE($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function vE($){return $ instanceof
|
|
80
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B$()||!u.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 lA(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=mw(this.config.logDirectory,J);if($.before)try{if((await nw(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 tA(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)}}}async function uE($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function vE($){return $ instanceof d$}function fT($){return $ instanceof GJ}function ZT($){if(vE($))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 yJ{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:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:W=!1,trackPerformance:Z=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let B=J||this.generateEnvPrefix($),h={...w};return this.processObject(h,[],B,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:W,configName:$}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(Z)return D1.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[U,Y]of Object.entries($)){let f=[...w,U],W=f.map((B)=>this.formatEnvKey(B,J.useCamelCase)),Z=`${A}_${W.join("_")}`,E=J.useBackwardCompatibility?`${A}_${f.map((B)=>B.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let B=pA.env[Z]||(E?pA.env[E]:void 0);if(B!==void 0){if(J.verbose){let h=pA.env[Z]?Z:E}try{$[U]=this.parseEnvironmentValue(B,typeof Y,Z,J.customParsers,J.configName)}catch(h){if(h instanceof qJ)throw h;throw s0.envVar(Z,B,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw s0.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(pA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;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(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],W=`${A}_${f.map((Z)=>this.formatEnvKey(Z,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:W,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}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 ZT($,w){let A=lE("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function nE($,w,A={}){return mE($,w,A,new WeakMap)}function mE($,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 dE($,w,U,J);if(!$0(w)||!$0($))return w;return hT($,w,A,J)}function dE($,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 WT($,w);case"smart":return ET($,w,J);default:return w}return w}function WT($,w){let A=[...w];for(let J of $)if(!A.some((U)=>A8(U,J)))A.push(J);return A}function ET($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return BT($,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 BT($,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 hT($,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]=mE(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=dE(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function R8($,w,A="replace"){return nE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function A8($,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(!A8($[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(!A8($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class LJ{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 E=rw.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!rA($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new O1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new O1($,Error("Configuration must export a valid object"),"unknown");let T={config:R8(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)rw.setWithFileCheck("file",T,$,Y);return T}catch(E){throw E instanceof Error?s0.configLoad($,E):s0.configLoad($,Error(String(E)))}};if(f)return D1.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(mY(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 uE(async()=>{return rA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!rA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=mY($,`${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=mY($,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(!rA($))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 K8{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await D1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!yH(w))throw new X1(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 X1(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:sE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class M8{fileLoader=new LJ;envProcessor=new yJ;validator=new K8;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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:E="replace",verbose:B=!1}=$,h=Y||Zw.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(Q$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw s0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),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 E=W?L1($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)E0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)E0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?L1($,A,U):A,W=[Q$(iw(),".config",$),Q$(iw(),".config"),iw()];for(let Z of W){if(U)E0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)E0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?L1($,J,Y):J;try{let Z=Q$(A,"package.json");if(!$8(Z))return null;let E=await import(Z),B=E[$],h=$;if(!B&&w)B=E[w],h=w;if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)E0.success(`Configuration loaded from package.json: ${h}`);return{config:R8(W,B,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:L1($,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 s0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return rw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);rw.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$(iw(),".config",$),Q$(iw(),".config"),iw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function zE($){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 FT($){return Q0.loadConfig({...$,__strictErrorHandling:!0})}async function gE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await Q0.loadConfig($);else J=await Q0.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 Q0.applyEnvironmentVariables(f.name||"",w,!0,f.verbose||!1))?.config??w;return w}}async function jT($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await Q0.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"&&zE(A)))return(await Q0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await Q0.loadConfig({...$,cwd:$.cwd||Zw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&zE(w)))return(await Q0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function zT($,w,A="replace"){let J=new LJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function L1($,w,A=!1){let J=new yJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=Zw.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function HT($){let w=Q$(Zw.cwd(),$.configDir),A=Q$(Zw.cwd(),$.generatedDir),J=Q$(A,"config-types.ts");if(!$8(gW(J)))AH(gW(J),{recursive:!0,mode:511});let U=$8(w)?JH(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${dT}
|
|
92
|
+
`;return A}}function WT($,w){let A=lE("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function nE($,w,A={}){return mE($,w,A,new WeakMap)}function mE($,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 dE($,w,U,J);if(!$0(w)||!$0($))return w;return FT($,w,A,J)}function dE($,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 ET($,w);case"smart":return BT($,w,J);default:return w}return w}function ET($,w){let A=[...w];for(let J of $)if(!A.some((U)=>A8(U,J)))A.push(J);return A}function BT($,w,A){if(w.length===0)return $;if($.length===0)return w;if($0(w[0])&&$0($[0]))return hT($,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 hT($,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 FT($,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]=mE(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=dE(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function R8($,w,A="replace"){return nE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function A8($,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(!A8($[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(!A8($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class LJ{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 E=rw.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!rA($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new O1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new O1($,Error("Configuration must export a valid object"),"unknown");let T={config:R8(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)rw.setWithFileCheck("file",T,$,Y);return T}catch(E){throw E instanceof Error?s0.configLoad($,E):s0.configLoad($,Error(String(E)))}};if(f)return D1.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(mY(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 uE(async()=>{return rA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!rA($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=mY($,`${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=mY($,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(!rA($))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 K8{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await D1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!LH(w))throw new X1(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 X1(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:sE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class M8{fileLoader=new LJ;envProcessor=new yJ;validator=new K8;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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:E="replace",verbose:B=!1}=$,h=Y||Zw.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(Q$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw s0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),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 E=W?L1($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)E0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)E0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?L1($,A,U):A,W=[Q$(iw(),".config",$),Q$(iw(),".config"),iw()];for(let Z of W){if(U)E0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)E0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?L1($,J,Y):J;try{let Z=Q$(A,"package.json");if(!$8(Z))return null;let E=await import(Z),B=E[$],h=$;if(!B&&w)B=E[w],h=w;if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)E0.success(`Configuration loaded from package.json: ${h}`);return{config:R8(W,B,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:L1($,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 s0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return rw.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);rw.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$(iw(),".config",$),Q$(iw(),".config"),iw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function zE($){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 jT($){return Q0.loadConfig({...$,__strictErrorHandling:!0})}async function gE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await Q0.loadConfig($);else J=await Q0.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 Q0.applyEnvironmentVariables(f.name||"",w,!0,f.verbose||!1))?.config??w;return w}}async function zT($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await Q0.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"&&zE(A)))return(await Q0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await Q0.loadConfig({...$,cwd:$.cwd||Zw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&zE(w)))return(await Q0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function HT($,w,A="replace"){let J=new LJ;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function L1($,w,A=!1){let J=new yJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=Zw.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function TT($){let w=Q$(Zw.cwd(),$.configDir),A=Q$(Zw.cwd(),$.generatedDir),J=Q$(A,"config-types.ts");if(!$8(gW(J)))JH(gW(J),{recursive:!0,mode:511});let U=$8(w)?UH(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${gT}
|
|
93
93
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
94
|
-
`;
|
|
94
|
+
`;YH(J,Y,{mode:438})}function GT($){let w=null,A=null,J=()=>{if(!A)A=gE($).then((Y)=>{return w=Y,Y},(Y)=>{let f="defaultConfig"in $?$.defaultConfig:{};if(w=f,"verbose"in $&&$.verbose)E0.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return f});return A},U="defaultConfig"in $?$.defaultConfig:{};return w=U,J(),new Proxy({},{get(Y,f){if(w)return w[f];let W=U[f];return J(),W},has(Y,f){return f in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(Y,f){return Object.getOwnPropertyDescriptor(w||U,f)},set(Y,f,W){if(!w)w={...U};return w[f]=W,!0}})}function qT($){let w=fE(OH.cwd(),$?.configDir||"./config");function A(){if(!SH(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],f=VH(w).filter((Z)=>U.has(dY(Z))).map((Z)=>({base:Z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Z})),W=new Map;for(let{base:Z,file:E}of f){let B=dY(E).toLowerCase(),h=W.get(Z);if(!h){W.set(Z,E);continue}let j=dY(h).toLowerCase();if(Y.indexOf(B)<Y.indexOf(j))W.set(Z,E)}return Array.from(W.entries()).map(([Z,E])=>({base:Z,file:E})).sort((Z,E)=>Z.base.localeCompare(E.base))}function J(){let U=A(),Y=U.map((Z)=>Z.base),f=Y.length?Y.map((Z)=>`'${Z}'`).join(" | "):"string",W=U.length?`{
|
|
95
95
|
${U.map((Z)=>{let E=fE(w,Z.file).replace(/\\/g,"/");return` '${Z.base}': typeof import('${E}').default`}).join(`,
|
|
96
96
|
`)}
|
|
97
97
|
}`:"Record<string, any>";return`export type ConfigNames = ${f}
|
|
98
98
|
export type ConfigByName = ${W}
|
|
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 lT($,w={}){let A=hJ.cwd();while(A.includes("storage"))A=ZE(A,"..");let J=ZE(A,$||"");if(w?.relative)return XH(hJ.cwd(),J);return J}function F$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pT(){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 wB{async format($){let w=await pT(),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:tw.pid,hostname:w(),environment:tw.env.NODE_ENV||"development",platform:tw.platform,version:tw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tw.env.NODE_ENV||tw.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;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={...NJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new wB,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,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{...eY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...eY};return{...eY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:NJ.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 xH(this.config.logDirectory,hE.F_OK|hE.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await PH(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(!aA(this.currentLogFile))await tY(this.currentLogFile,"",{mode:420});if(J=BE(this.currentLogFile,"a",420),QH(J,W,{flag:"a"}),EE(J),J!==void 0)lY(J),J=void 0;if((await gw(this.currentLogFile)).size===0){if(await tY(this.currentLogFile,W,{flag:"w",mode:420}),(await gw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let B=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,B);let h=f*2**U;await new Promise((j)=>setTimeout(j,h)),U++;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{lY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let E=W,B=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),W}U++;let Z=f*2**(U-1);await new Promise((E)=>setTimeout(E,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 lw(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 lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return lw(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 gY(16).toString("hex")}generateKey(){return gY(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=gY(16),J=_H("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(),E=V0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=jE(),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(F$())return;if(!this.shouldWriteToFile())return;let $=await gw(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 sA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await gw(A).catch(()=>null))try{if(await FE(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await oA(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 gw(A).catch(()=>null))await FE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await sA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await oA(lw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=WE($),J=kH(w),U=jE();await cH(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()})),aA(this.currentLogFile))try{let $=BE(this.currentLogFile,"r+");EE($),lY($)}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 sA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await oA(lw(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()?P.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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=v.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${P.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(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(bH(w)||w.startsWith("./")||w.startsWith("../"))w=iH(w);else return null;return aA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":eT[$],j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:P.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:P.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
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 tT($,w={}){let A=hJ.cwd();while(A.includes("storage"))A=ZE(A,"..");let J=ZE(A,$||"");if(w?.relative)return _H(hJ.cwd(),J);return J}function F$(){if(D0.env.NODE_ENV==="test"||D0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function rT(){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 wB{async format($){let w=await rT(),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:tw.pid,hostname:w(),environment:tw.env.NODE_ENV||"development",platform:tw.platform,version:tw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tw.env.NODE_ENV||tw.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;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={...NJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new wB,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,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{...eY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...eY};return{...eY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:NJ.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 PH(this.config.logDirectory,hE.F_OK|hE.W_OK)}catch(Z){if(Z instanceof Error&&"code"in Z)if(Z.code==="ENOENT")await bH(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(!aA(this.currentLogFile))await tY(this.currentLogFile,"",{mode:420});if(J=BE(this.currentLogFile,"a",420),xH(J,W,{flag:"a"}),EE(J),J!==void 0)lY(J),J=void 0;if((await gw(this.currentLogFile)).size===0){if(await tY(this.currentLogFile,W,{flag:"w",mode:420}),(await gw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Z){let E=Z;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(U<Y-1){let B=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${Y}:`,B);let h=f*2**U;await new Promise((j)=>setTimeout(j,h)),U++;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{lY(J)}catch(Z){console.error("Debug: [writeToFile] Error closing file descriptor:",Z)}}}catch(W){if(U===Y-1){let E=W,B=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),W}U++;let Z=f*2**(U-1);await new Promise((E)=>setTimeout(E,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 lw(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 lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return lw(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 gY(16).toString("hex")}generateKey(){return gY(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=gY(16),J=DH("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(),E=V0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=jE(),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(F$())return;if(!this.shouldWriteToFile())return;let $=await gw(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 sA(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await gw(A).catch(()=>null))try{if(await FE(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await oA(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 gw(A).catch(()=>null))await FE(A,Y)}if(this.currentLogFile=J,w.maxFiles){let U=(await sA(this.config.logDirectory)).filter((Y)=>Y.startsWith(this.name)).sort((Y,f)=>f.localeCompare(Y));for(let Y of U.slice(w.maxFiles))await oA(lw(this.config.logDirectory,Y))}}}async compressLogFile($,w){let A=WE($),J=QH(w),U=jE();await uH(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()})),aA(this.currentLogFile))try{let $=BE(this.currentLogFile,"r+");EE($),lY($)}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 sA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await oA(lw(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()?P.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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=v.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${P.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(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(iH(w)||w.startsWith("./")||w.startsWith("../"))w=cH(w);else return null;return aA(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":$G[$],j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:P.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:P.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
102
102
|
`);for(let H of T)if(H.trim()&&!H.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:P.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!F$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}let B=`${Y} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
103
103
|
`;if(W)B+=`${W}
|
|
104
104
|
`;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,w=""){let A={update:(U,Y)=>{},finish:(U)=>{},interrupt:(U,Y)=>{}};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$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,Y)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),Y!==void 0)this.activeProgressBar.message=Y;if(this.shouldStyleConsole()&&!F$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,Y="info")=>{if(!F$()&&v.stdout.isTTY)v.stdout.write(`
|
|
105
105
|
`);if(this[Y==="warning"?"warn":Y](U),this.activeProgressBar&&this.shouldStyleConsole()&&!F$()&&v.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),Z=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)Z+=` ${JSON.stringify(A)}`;if(Z+=`
|
|
106
|
-
`,Z=Z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:E,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F$())console.error(Z.trim());if(this.shouldWriteToFile())await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new SJ(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(!aA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return WE(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=V0.isBuffer($)?$:V0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=
|
|
106
|
+
`,Z=Z.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:E,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!F$())console.error(Z.trim());if(this.shouldWriteToFile())await this.writeToFile(Z)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new SJ(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(!aA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return WE(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=V0.isBuffer($)?$:V0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=kH("aes-256-gcm",A,U);W.setAuthTag(Y);let Z=W.update(f),E=W.final(),B=Z.length+E.length,h=V0.allocUnsafe(B);return Z.copy(h,0),E.copy(h,Z.length),h.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:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
107
107
|
`),Z=Math.max(...W.map((j)=>j.length))+2,E=`┌${"─".repeat(Z)}┐`,B=`└${"─".repeat(Z)}┘`,h=W.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(E),showTimestamp:!1})),h.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(B),showTimestamp:!1}))}else if(!F$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
108
108
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(F$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=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(U==="y"||U==="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 f=/%([sdijfo%])/g,W=0;if(A=$.replace(f,(Z,E)=>{if(E==="%")return"%";if(W>=w.length)return Z;let B=w[W++];switch(E){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 Z}}),W<w.length)A+=` ${w.slice(W).map((Z)=>typeof Z==="object"?JSON.stringify(Z,null,2):String(Z)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${W}${f} ${P.cyan(J)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
109
109
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Y)}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),U=$.barLength-J,Y=P.green("━".repeat(J)),f=P.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=v.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,v.stdout.write($.lastRenderedLine),w)v.stdout.write(`
|
|
110
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!v.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await sA(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=lw(this.config.logDirectory,J);if($.before)try{if((await gw(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 oA(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)}}}async function
|
|
110
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F$()||!v.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await sA(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=lw(this.config.logDirectory,J);if($.before)try{if((await gw(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 oA(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)}}}async function wG($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}class C8{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:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:W=!1,trackPerformance:Z=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let B=J||this.generateEnvPrefix($),h={...w};return this.processObject(h,[],B,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:W,configName:$}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(Z)return H8.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[U,Y]of Object.entries($)){let f=[...w,U],W=f.map((B)=>this.formatEnvKey(B,J.useCamelCase)),Z=`${A}_${W.join("_")}`,E=J.useBackwardCompatibility?`${A}_${f.map((B)=>B.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let B=eA.env[Z]||(E?eA.env[E]:void 0);if(B!==void 0){if(J.verbose){let h=eA.env[Z]?Z:E}try{$[U]=this.parseEnvironmentValue(B,typeof Y,Z,J.customParsers,J.configName)}catch(h){if(h instanceof I8)throw h;throw aw.envVar(Z,B,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw aw.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(eA.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;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(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],W=`${A}_${f.map((Z)=>this.formatEnvKey(Z,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:W,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}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 wG($,w,A={}){return EB($,w,A,new WeakMap)}function EB($,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 BB($,w,U,J);if(!w0(w)||!w0($))return w;return YG($,w,A,J)}function BB($,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 AG($,w);case"smart":return JG($,w,J);default:return w}return w}function AG($,w){let A=[...w];for(let J of $)if(!A.some((U)=>h8(U,J)))A.push(J);return A}function JG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(w0(w[0])&&w0($[0]))return UG($,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 UG($,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 YG($,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]=EB(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=BB(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function hB($,w,A="replace"){return wG($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function h8($,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(!h8($[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(!h8($[U],w[U]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class FB{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 E=FJ.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!$J($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new RJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new RJ($,Error("Configuration must export a valid object"),"unknown");let T={config:hB(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)FJ.setWithFileCheck("file",T,$,Y);return T}catch(E){throw E instanceof Error?aw.configLoad($,E):aw.configLoad($,Error(String(E)))}};if(f)return H8.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(pY(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 $G(async()=>{return $J($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!$J($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=pY($,`${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=pY($,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(!$J($))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 jB{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await H8.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!uH(w))throw new KJ(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 KJ(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:fG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function ZG($){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 zB{fileLoader=new FB;envProcessor=new C8;validator=new jB;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)O0.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 O0.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:E="replace",verbose:B=!1}=$,h=Y||CJ.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(e$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw aw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),warnings:[`No configuration file found for "${J}"${ZG(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let E=W?AJ($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)O0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)O0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?AJ($,A,U):A,W=[e$(bw(),".config",$),e$(bw(),".config"),bw()];for(let Z of W){if(U)O0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)O0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?AJ($,J,Y):J;try{let Z=e$(A,"package.json");if(!$H(Z))return null;let E={};try{E=JSON.parse(wH(Z,"utf8"))}catch(j){if(Y)O0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let B=E[$],h=$;if(!B&&w){let j=Array.isArray(w)?w:[w];for(let F of j){if(!F)continue;if(E[F]){B=E[F],h=F;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)O0.success(`Configuration loaded from package.json: ${h}`);return{config:hB(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)O0.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:AJ($,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 aw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return FJ.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);FJ.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$(bw(),".config",$),e$(bw(),".config"),bw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function AJ($,w,A=!1){let J=new C8,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=CJ.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function F8($,w){let A=[];function J(U){let Y;try{Y=SE.readdirSync(U)}catch{return}for(let f of Y){let W=W0.join(U,f);try{if(SE.statSync(W).isDirectory())J(W);else if(f===w)A.push(U)}catch{continue}}}return J($),A}function M($,w,A){if(A||J$.verbose)console.debug(`[tlsx:${$}] ${w}`)}function GB(){return TB.env.SUDO_PASSWORD}function zG($){let w=$.toLowerCase();return FG.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function MJ($){if(Array.isArray($))return $.map((A)=>MJ(A));if(typeof $==="string")return jG.test($)?VE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(zG(A)){w[A]=VE;continue}w[A]=MJ(J)}return w}function VJ($){return JSON.stringify(MJ($))}function HG($){let w=GB();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 a0($,w={}){let A=HG($);try{let{stdout:J,stderr:U}=await hG(A,{cwd:w.cwd||TB.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 U.stack=J.stack,U}}function qB($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function y8($){let w=W0.join(
|
|
122
|
+
`;return A}}function AG($,w,A={}){return EB($,w,A,new WeakMap)}function EB($,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 BB($,w,U,J);if(!w0(w)||!w0($))return w;return fG($,w,A,J)}function BB($,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 JG($,w);case"smart":return UG($,w,J);default:return w}return w}function JG($,w){let A=[...w];for(let J of $)if(!A.some((U)=>h8(U,J)))A.push(J);return A}function UG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(w0(w[0])&&w0($[0]))return YG($,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 YG($,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 fG($,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]=EB(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=BB(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function hB($,w,A="replace"){return AG($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function h8($,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(!h8($[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(!h8($[U],w[U]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class FB{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 E=FJ.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!$J($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new RJ($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new RJ($,Error("Configuration must export a valid object"),"unknown");let T={config:hB(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)FJ.setWithFileCheck("file",T,$,Y);return T}catch(E){throw E instanceof Error?aw.configLoad($,E):aw.configLoad($,Error(String(E)))}};if(f)return H8.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(pY(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 wG(async()=>{return $J($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!$J($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=pY($,`${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=pY($,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(!$J($))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 jB{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await H8.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!vH(w))throw new KJ(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 KJ(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:ZG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function WG($){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 zB{fileLoader=new FB;envProcessor=new C8;validator=new jB;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)O0.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 O0.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:E="replace",verbose:B=!1}=$,h=Y||CJ.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(e$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw aw.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),warnings:[`No configuration file found for "${J}"${WG(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,J,U,Y,f,W,Z){let E=W?AJ($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)O0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)O0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?AJ($,A,U):A,W=[e$(bw(),".config",$),e$(bw(),".config"),bw()];for(let Z of W){if(U)O0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)O0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?AJ($,J,Y):J;try{let Z=e$(A,"package.json");if(!wH(Z))return null;let E={};try{E=JSON.parse(AH(Z,"utf8"))}catch(j){if(Y)O0.warn("Failed to parse package.json:",[j instanceof Error?j:Error(String(j))]);return null}let B=E[$],h=$;if(!B&&w){let j=Array.isArray(w)?w:[w];for(let F of j){if(!F)continue;if(E[F]){B=E[F],h=F;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)O0.success(`Configuration loaded from package.json: ${h}`);return{config:hB(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)O0.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:AJ($,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 aw.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return FJ.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);FJ.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$(bw(),".config",$),e$(bw(),".config"),bw()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function AJ($,w,A=!1){let J=new C8,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=CJ.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function F8($,w){let A=[];function J(U){let Y;try{Y=SE.readdirSync(U)}catch{return}for(let f of Y){let W=W0.join(U,f);try{if(SE.statSync(W).isDirectory())J(W);else if(f===w)A.push(U)}catch{continue}}}return J($),A}function M($,w,A){if(A||J$.verbose)console.debug(`[tlsx:${$}] ${w}`)}function GB(){return TB.env.SUDO_PASSWORD}function HG($){let w=$.toLowerCase();return jG.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function MJ($){if(Array.isArray($))return $.map((A)=>MJ(A));if(typeof $==="string")return zG.test($)?VE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(HG(A)){w[A]=VE;continue}w[A]=MJ(J)}return w}function VJ($){return JSON.stringify(MJ($))}function TG($){let w=GB();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 a0($,w={}){let A=TG($);try{let{stdout:J,stderr:U}=await FG(A,{cwd:w.cwd||TB.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 U.stack=J.stack,U}}function qB($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function y8($){let w=W0.join(BG.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:J$.basePath&&J$.basePath.trim()!==""?J$.basePath:w,J=$.certPath?W0.isAbsolute($.certPath)?$.certPath:W0.join(A,$.certPath):W0.join(A,J$.certPath),U=$.keyPath?W0.isAbsolute($.keyPath)?$.keyPath:W0.join(A,$.keyPath):W0.join(A,J$.keyPath),Y=$.caCertPath?W0.isAbsolute($.caCertPath)?$.caCertPath:W0.join(A,$.caCertPath):W0.join(A,J$.caCertPath);return{certPath:J,keyPath:U,caCertPath:Y,basePath:A}}function NB($){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 M(I.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function L8($){let w=$.notBeforeDays??B0.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:B0.DEFAULT_VALIDITY_DAYS);M(I.CERT,"Calculating certificate validity dates",$.verbose);let J=new Date(Date.now()-86400*w*1000),U=new Date(J.getTime()+A*24*60*60*1000);return J.setUTCHours(0,0,0,0),U.setUTCHours(23,59,59,999),M(I.CERT,`Validity period: ${J.toISOString()} to ${U.toISOString()}`,$.verbose),{notBefore:J,notAfter:U}}function S1($){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 l$($,w){let A=S1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function _1($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let J=2;J<w.length;J++){let U=w[J],Y=[];Y.unshift(U&127),U>>=7;while(U>0)Y.unshift(U&127|128),U>>=7;A.push(...Y)}return l$(h0.OID,Buffer.from(A))}function j8($){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 l$(h0.INTEGER,w)}function RB($,w=0){return l$(h0.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function KB($){return l$(h0.OCTET_STRING,$)}function g$(...$){return l$(h0.SEQUENCE,Buffer.concat($))}function GG(...$){return l$(h0.SET,Buffer.concat($))}function qG($){return l$(h0.PRINTABLE_STRING,Buffer.from($,"ascii"))}function NG($){return l$(h0.UTF8_STRING,Buffer.from($,"utf8"))}function RG(){return Buffer.from([h0.NULL,0])}function OE($,w,A=!0){let J=160|$|(A?0:0),U=S1(w.length);return Buffer.concat([Buffer.from([J]),U,w])}function XE($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return l$(h0.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),J=($.getUTCMonth()+1).toString().padStart(2,"0"),U=$.getUTCDate().toString().padStart(2,"0"),Y=$.getUTCHours().toString().padStart(2,"0"),f=$.getUTCMinutes().toString().padStart(2,"0"),W=$.getUTCSeconds().toString().padStart(2,"0"),Z=`${A}${J}${U}${Y}${f}${W}Z`;return l$(h0.UTC_TIME,Buffer.from(Z,"ascii"))}}function KG($,w){return g$(XE($),XE(w))}function _E($){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 U=A.shortName==="C"?qG(A.value):NG(A.value),Y=g$(_1(J),U);w.push(GG(Y))}return g$(...w)}function MB($){return g$(_1($),RG())}function MG($){return $.export({type:"spki",format:"der"})}function IG($){if($.includes(":")){let w=$;if($.includes("::")){let U=$.split("::"),Y=U[0]?U[0].split(":"):[],f=U[1]?U[1].split(":"):[],W=8-Y.length-f.length,Z=Array.from({length:W},()=>"0");w=[...Y,...Z,...f].join(":")}let A=w.split(":"),J=Buffer.alloc(16);for(let U=0;U<8;U++){let Y=Number.parseInt(A[U]||"0",16);J.writeUInt16BE(Y,U*2)}return J}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function CG($){let w=[];for(let A of $)if(A.type===2&&A.value){let J=S1(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=IG(A.ip),U=S1(J.length);w.push(Buffer.concat([Buffer.from([135]),U,J]))}else if(A.type===6&&A.value){let J=S1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),J,Buffer.from(A.value,"ascii")]))}return g$(...w)}function yG($,w){if($){if(w!==void 0)return g$(l$(1,Buffer.from([255])),j8(w));return g$(l$(1,Buffer.from([255])))}return g$()}function LG($){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 RB(Buffer.from([w]),A)}function SG($){let w=[];if($.serverAuth)w.push(_1(x$.SERVER_AUTH));if($.clientAuth)w.push(_1(x$.CLIENT_AUTH));return g$(...w)}function y1($,w,A){let J=[_1($)];if(w)J.push(l$(1,Buffer.from([255])));return J.push(KB(A)),g$(...J)}function VG($){let w=[];if(w.push(OE(0,j8(2))),w.push(j8($.serialNumber)),w.push(MB(x$.SHA256_WITH_RSA)),w.push(_E($.issuer)),w.push(KG($.notBefore,$.notAfter)),w.push(_E($.subject)),w.push(MG($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(y1(x$.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,yG($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(y1(x$.KEY_USAGE,$.extensions.keyUsage.critical??!0,LG($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(y1(x$.EXTENDED_KEY_USAGE,!1,SG($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(y1(x$.SUBJECT_ALT_NAME,!1,CG($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(y1(x$.SUBJECT_KEY_IDENTIFIER,!1,KB($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push(OE(3,g$(...A)))}return g$(...w)}function OG($,w){let A=sw.createSign("SHA256");A.update($);let J=A.sign(w);return g$($,MB(x$.SHA256_WITH_RSA),RB(J))}function XG($,w){let A=$.toString("base64"),J=[];for(let U=0;U<A.length;U+=64)J.push(A.slice(U,U+64));return`-----BEGIN ${w}-----
|
|
124
124
|
${J.join(`
|
|
125
125
|
`)}
|
|
126
126
|
-----END ${w}-----
|
|
127
|
-
`}function S8(){return sw.randomBytes(20)}function IB($=2048){let{privateKey:w,publicKey:A}=sw.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}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 V8($={}){M("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||B0.DEFAULT_KEY_SIZE;M("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=IB(w),U=[{shortName:"C",value:$.countryName||J$.countryName},{shortName:"ST",value:$.stateName||J$.stateName},{shortName:"L",value:$.localityName||J$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:Y,notAfter:f}=L8({validityYears:$.validityYears||B0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=CB({serialNumber:S8(),notBefore:Y,notAfter:f,subject:U,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:yB(A),notBefore:Y,notAfter:f}}async function O8($){if(M("ca","Generating new certificate",$.verbose),M("ca",`Options: ${VJ($)}`,$.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}=DG($.rootCA.certificate),A=_G($.rootCA.privateKey);M("ca",`Generating ${B0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=B0.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:Y}=IB(J),f=$.commonName||qB($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||J$.countryName},{shortName:"ST",value:$.stateName||J$.stateName},{shortName:"L",value:$.localityName||J$.localityName},{shortName:"O",value:$.organizationName||J$.organizationName},{shortName:"CN",value:f}],{notBefore:Z,notAfter:E}=L8({validityDays:$.validityDays||B0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),B=NB($),h=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},j=$.extKeyUsage||{serverAuth:!0},{certificate:F}=CB({serialNumber:S8(),notBefore:Z,notAfter:E,subject:W,issuer:w,publicKey:Y,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:h,extendedKeyUsage:j,subjectAltName:B});return{certificate:F,privateKey:yB(U),notBefore:Z,notAfter:E}}function LB($,w){M(I.STORAGE,`Storing certificate and private key with options: ${VJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=y8({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=z8.dirname(A);if(!k0.existsSync(U))M(I.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),k0.mkdirSync(U,{recursive:!0});M(I.STORAGE,"Writing certificate file",w?.verbose),k0.writeFileSync(A,$.certificate);let Y=z8.dirname(J);if(!k0.existsSync(Y))M(I.STORAGE,`Creating private key directory: ${Y}`,w?.verbose),k0.mkdirSync(Y,{recursive:!0});return M(I.STORAGE,"Writing private key file",w?.verbose),k0.writeFileSync(J,$.privateKey),M(I.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function SB($,w){M(I.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=y8({basePath:w?.basePath,caCertPath:w?.caCertPath});M(I.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=z8.dirname(A);if(!k0.existsSync(J))M(I.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),k0.mkdirSync(J,{recursive:!0});return M(I.STORAGE,"Writing CA certificate file",w?.verbose),k0.writeFileSync(A,$),M(I.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function kG($,w){if(IJ.platform()!=="darwin")return!1;try{let A=DE(`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(DE("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 X8($,w,A){M(I.TRUST,`Adding certificate to system trust store with options: ${VJ(A)}`,A?.verbose),M(I.TRUST,"Storing certificate and private key",A?.verbose);let J=LB($,A);M(I.TRUST,"Storing CA certificate",A?.verbose);let U=SB(w,A),Y=IJ.platform();M(I.TRUST,`Detected platform: ${Y}`,A?.verbose);let f=bG[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 SN,FJ,H8,vH,nH=($)=>$,dH=($,w)=>{for(var A in w)vH($,A,{get:w[A],enumerable:!0,configurable:!0,set:mH.bind(w,A)})},gH=($,w)=>()=>($&&(w=$($=0)),w),bE,lE,rw,D1,tE,qT,NT,HE,UJ,J8,C$,g,RT,TE,KT,GE,MT,IT,rY,CT,qE,NE,aY,yT,LT,ST,VT,YJ,pE,OT,y$,XT,_T,RE,fJ,U8,h$,k,DT,KE,kT,ME,QT,xT,sY,PT,IE,CE,bT,oY,iT,cT,uT,vT,nT,ZJ,rE,mT,dT="0.15.6",m$,GJ,O1,Y8,f8,qJ,Z8,W8,X1,E8,B8,s0,aE,sE,E0,Q0,oE,eE,gT,tT,$B,NJ,oR,q$,P,eR,rT,$K,aT,wK,AK,yE,JK,sT,oT,UK,LE,YK,fK,ZK,WK,EK,eY,eT,BK,F0,AB,RJ,JB,UB,I8,YB,fB,KJ,ZB,WB,aw,fG,O0,hK,FK,jK,HB,J$,B0,I,pw,hG,VE="[redacted]",FG,jG,h0,x$,QG,xG,PG,bG;var VB=X$(()=>{SN=e9(import.meta.url);FJ=new xE,H8=new PE,vH=Object.defineProperty;bE={};dH(bE,{withErrorRecovery:()=>uE,tryLoadConfig:()=>zT,loadConfigWithResult:()=>FT,loadConfig:()=>gE,isRetryableError:()=>fT,isConfigNotFoundError:()=>YT,isBunfigError:()=>vE,globalPerformanceMonitor:()=>D1,globalCache:()=>rw,getEnvOrDefault:()=>ZT,generateConfigTypes:()=>HT,defaultGeneratedDir:()=>eE,defaultConfigDir:()=>oE,deepMergeWithArrayStrategy:()=>R8,deepMerge:()=>nE,createLibraryConfig:()=>TT,config:()=>jT,bunfigPlugin:()=>GT,applyEnvVarsToConfig:()=>L1,TypeGenerationError:()=>W8,SchemaValidationError:()=>X1,PluginError:()=>B8,PerformanceMonitor:()=>G8,FileSystemError:()=>Z8,ErrorFactory:()=>s0,EnvVarError:()=>qJ,EnvProcessor:()=>yJ,ConfigValidator:()=>K8,ConfigValidationError:()=>Y8,ConfigNotFoundError:()=>GJ,ConfigMergeError:()=>f8,ConfigLoader:()=>M8,ConfigLoadError:()=>O1,ConfigFileLoader:()=>LJ,ConfigCache:()=>T8,CacheUtils:()=>tE,BunfigError:()=>m$,BrowserConfigError:()=>E8,ArrayMergeStrategies:()=>aE});gT=gH(async()=>{lE=import.meta.require,rw=new T8,D1=new G8,tE={createKey:lH,isEquivalent:tH,estimateMemoryUsage:pH},qT=BJ(w8.cwd(),"config"),NT=BJ(w8.cwd(),"src/generated"),HE=EJ.env.CLARITY_LOG_DIR||ZH(sH(),"logs"),UJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:HE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},J8=await oH(),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"},g=C$,RT=C$.red,TE=C$.green,KT=C$.yellow,GE=C$.blue,MT=C$.magenta,IT=C$.cyan,rY=C$.white,CT=C$.gray,qE=C$.bgRed,NE=C$.bgYellow,aY=C$.bold,yT=C$.dim,LT=C$.italic,ST=C$.underline,VT=C$.reset,YJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pE={debug:"\uD83D\uDD0D",info:GE("ℹ"),success:TE("✓"),warning:NE(rY(aY(" WARN "))),error:qE(rY(aY(" ERROR ")))},OT=new zJ("stacks"),y$=new zJ("bunfig",{showTags:!0}),XT=k$(V1.cwd(),"config"),_T=k$(V1.cwd(),"src/generated"),RE=WJ.env.CLARITY_LOG_DIR||YH(AT(),"logs"),fJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:RE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},U8=await JT(),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"},k=h$,DT=h$.red,KE=h$.green,kT=h$.yellow,ME=h$.blue,QT=h$.magenta,xT=h$.cyan,sY=h$.white,PT=h$.gray,IE=h$.bgRed,CE=h$.bgYellow,bT=h$.bgGray,oY=h$.bold,iT=h$.dim,cT=h$.italic,uT=h$.underline,vT=h$.strikethrough,nT=h$.reset,ZJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rE={debug:"\uD83D\uDD0D",info:ME("ℹ"),success:KE("✓"),warning:CE(sY(oY(" WARN "))),error:IE(sY(oY(" ERROR ")))},mT=new TJ("stacks"),m$=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}${$}`}},GJ=class extends m${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})}},O1=class extends m${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}},Y8=class extends m${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},f8=class extends m${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}},qJ=class extends m${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})}},Z8=class extends m${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}},W8=class extends m${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}},X1=class extends m${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 m${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},B8=class extends m${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}},s0={configNotFound($,w,A){return new GJ($,w,A)},configLoad($,w,A){return new O1($,w,A)},configValidation($,w,A){return new Y8($,w,A)},configMerge($,w,A,J){return new f8($,w,A,J)},envVar($,w,A,J){return new qJ($,w,A,J)},fileSystem($,w,A){return new Z8($,w,A)},typeGeneration($,w,A){return new W8($,w,A)},schemaValidation($,w,A){return new X1($,w,A)},browserConfig($,w,A,J){return new E8($,w,A,J)},plugin($,w,A){return new B8($,w,A)}},aE={replace:"replace",concat:"concat",smart:"smart"},sE=/^https?:\/\//,E0=new TJ("bunfig",{showTags:!0}),Q0=new M8,oE=Q$(Zw.cwd(),"config"),eE=Q$(Zw.cwd(),"src/generated")});tT=hJ.env.CLARITY_LOG_DIR||OH(lT(),"logs"),$B={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:tT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},NJ={...$B},oR=(async()=>{try{let{loadConfig:$}=await gT().then(()=>bE),w=await $({name:"clarity",alias:"logging",defaultConfig:$B,cwd:hJ.cwd()});if(w)Object.assign(NJ,w)}catch{}return NJ})();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"},P=q$,eR=q$.red,rT=q$.green,$K=q$.yellow,aT=q$.blue,wK=q$.magenta,AK=q$.cyan,yE=q$.white,JK=q$.gray,sT=q$.bgRed,oT=q$.bgYellow,UK=q$.bgGray,LE=q$.bold,YK=q$.dim,fK=q$.italic,ZK=q$.underline,WK=q$.strikethrough,EK=q$.reset,eY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},eT={debug:"\uD83D\uDD0D",info:aT("ℹ"),success:rT("✓"),warning:oT(yE(LE(" WARN "))),error:sT(yE(LE(" ERROR ")))};BK=new SJ("stacks");F0=class F0 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}${$}`}};AB=class AB extends F0{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 F0{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}};JB=class JB extends F0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};UB=class UB extends F0{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}};I8=class I8 extends F0{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})}};YB=class YB extends F0{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}};fB=class fB extends F0{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}};KJ=class KJ extends F0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};ZB=class ZB extends F0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}};WB=class WB extends F0{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}};aw={configNotFound($,w,A){return new AB($,w,A)},configLoad($,w,A){return new RJ($,w,A)},configValidation($,w,A){return new JB($,w,A)},configMerge($,w,A,J){return new UB($,w,A,J)},envVar($,w,A,J){return new I8($,w,A,J)},fileSystem($,w,A){return new YB($,w,A)},typeGeneration($,w,A){return new fB($,w,A)},schemaValidation($,w,A){return new KJ($,w,A)},browserConfig($,w,A,J){return new ZB($,w,A,J)},plugin($,w,A){return new WB($,w,A)}};fG=/^https?:\/\//;O0=new SJ("bunfig",{showTags:!0});hK=new zB;FK=e$(CJ.cwd(),"config"),jK=e$(CJ.cwd(),"src/generated"),HB={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:QY.join(kY.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:QY.join(kY.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:QY.join(kY.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},J$=HB,B0={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"},pw={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};hG=BG(WG);FG=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),jG=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;h0={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"};QG={platform:"darwin",async addCertificate($,w){if(await kG($,w?.verbose)){M(I.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),pw.success("Certificate is already trusted in system keychain");return}M(I.TRUST,"Adding certificate to macOS keychain",w?.verbose),await a0(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||J$.commonName;M(I.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await a0(`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}}},xG={platform:"win32",async addCertificate($,w){M(I.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await a0(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||J$.commonName;M(I.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await a0(`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}}},PG={platform:"linux",async addCertificate($,w){M(I.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=IJ.homedir(),J=B0.LINUX_CERT_DB_FILENAME,U=B0.LINUX_TRUST_ARGS;M(I.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let Y=F8(A,J);if(Y.length===0){pw.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 ${J$.commonName}`,w?.verbose),await a0(`certutil -d sql:${f} -D -n ${J$.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 a0(`certutil -d sql:${f} -A -t ${U} -n ${J$.commonName} -i ${$}`),pw.info(`Cert added to ${f}`)}},async removeCertificate($,w,A){let J=A||J$.commonName;M(I.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let U=IJ.homedir(),Y=B0.LINUX_CERT_DB_FILENAME;M(I.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let f=F8(U,Y);if(f.length===0){pw.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 a0(`certutil -d sql:${W} -D -n "${J}"`),pw.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}`)}}}},bG={darwin:QG,win32:xG,linux:PG}});var OB=X$(()=>{VB()});import{homedir as _8}from"node:os";import{join as D8,resolve as AM}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",iG,k8;var Q8=X$(()=>{XY();iG={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:D8(_8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:D8(_8(),".stacks","ssl","stacks.localhost.crt"),keyPath:D8(_8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},k8=iG});import{execSync as cG}from"node:child_process";function XB($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function OJ($){try{let w=cG(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return XB(w)}catch{return null}}var x8=()=>{};import{existsSync as _B,statSync as DB}from"fs";import{existsSync as $f,mkdirSync as gG,readdirSync as lG,writeFileSync as tG}from"fs";import{homedir as ow}from"os";import{dirname as kB,resolve as b$}from"path";import Ww from"process";import{join as pG,relative as rG,resolve as QB}from"path";import lJ from"process";import{existsSync as Th,mkdirSync as HM,readdirSync as TM,writeFileSync as GM}from"fs";import{homedir as P8}from"os";import{dirname as RM,resolve as P$}from"path";import Q1 from"process";import{join as aG,relative as sG,resolve as xB}from"path";import tJ from"process";import{existsSync as Gh,mkdirSync as yM,readdirSync as LM,writeFileSync as SM}from"fs";import{dirname as OM,resolve as pJ}from"path";import wf from"process";import{Buffer as o0}from"buffer";import{createCipheriv as oG,createDecipheriv as eG,randomBytes as b8}from"crypto";import{closeSync as i8,createReadStream as PB,createWriteStream as $2,existsSync as c8,fsyncSync as bB,openSync as iB,writeFileSync as w2}from"fs";import{access as A2,constants as cB,mkdir as J2,readdir as XJ,rename as uB,stat as ew,unlink as _J,writeFile as u8}from"fs/promises";import{join as $1}from"path";import L$ from"process";import{pipeline as U2}from"stream/promises";import{createGzip as vB}from"zlib";import w1 from"process";import b0 from"process";import{Buffer as x0}from"buffer";import{createCipheriv as Y2,createDecipheriv as f2,randomBytes as v8}from"crypto";import{closeSync as n8,createReadStream as nB,createWriteStream as Z2,existsSync as DJ,fsyncSync as mB,openSync as dB,writeFileSync as W2}from"fs";import{access as E2,constants as gB,mkdir as B2,readdir as kJ,rename as lB,stat as A1,unlink as QJ,writeFile as m8}from"fs/promises";import{isAbsolute as h2,join as J1,resolve as F2}from"path";import X from"process";import{pipeline as j2}from"stream/promises";import{createGzip as tB}from"zlib";import U1 from"process";import i0 from"process";import xJ from"process";import{existsSync as PJ}from"fs";import{resolve as d8}from"path";import{existsSync as z2}from"fs";import{existsSync as H2,readdirSync as T2}from"fs";import{extname as g8,resolve as pB}from"path";import G2 from"process";import{join as q7,relative as N7,resolve as fh}from"path";import wU from"process";import{Buffer as P0}from"buffer";import{createCipheriv as M7,createDecipheriv as I7,randomBytes as a8}from"crypto";import{closeSync as s8,createReadStream as Zh,createWriteStream as C7,existsSync as iJ,fsyncSync as Wh,openSync as Eh,writeFileSync as y7}from"fs";import{access as L7,constants as Bh,mkdir as S7,readdir as cJ,rename as hh,stat as Y1,unlink as uJ,writeFile as o8}from"fs/promises";import{isAbsolute as V7,join as f1,resolve as O7}from"path";import _ from"process";import{pipeline as X7}from"stream/promises";import{createGzip as Fh}from"zlib";import Z1 from"process";import c0 from"process";function nG($,w){this[$]=vG.bind(null,w)}class hf{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(!_B($))return!0;return DB($).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=_B(A)?DB(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 Ff{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 q2($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function N2($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function R2($){return $.getStats().size*2}function jf($,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((f)=>a(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(a(U)&&"path"in U){if(!J.find((f)=>a(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>rJ(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]=jf(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((Z)=>a(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(a(f)&&"path"in f){if(!Y.find((Z)=>a(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>rJ(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 rJ($,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(!rJ($[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(!rJ($[U],w[U]))return!1}return!0}return!1}function a($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function K2($,w){if(!Gh($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return jf(w,J)}catch{return null}}catch{return null}}async function M2({name:$="",cwd:w,defaultConfig:A}){let J=w||wf.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=pJ(J,`${f}${W}`),E=await K2(Z,A);if(E!==null)return E}try{let f=pJ(J,"package.json");if(Gh(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return jf(A,Z)}catch{}}}catch{}return A}function I2($,w={}){let A=tJ.cwd();while(A.includes("storage"))A=xB(A,"..");let J=xB(A,$||"");if(w?.relative)return sG(tJ.cwd(),J);return J}async function C2(){try{let $=await M2({name:"clarity",defaultConfig:nJ,cwd:tJ.cwd(),endpoint:"",headers:{}});return{...nJ,...$}}catch{return nJ}}function w$(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function y2(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b0<"u"){let $=b0.type;if($==="renderer"||$==="worker")return!1;return!!(b0.versions&&(b0.versions.node||b0.versions.bun))}return!1}class qh{async format($){let w=await y2(),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:w1.pid,hostname:w(),environment:w1.env.NODE_ENV||"development",platform:w1.platform,version:w1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:w1.env.NODE_ENV||w1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class aJ{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={...Jf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new qh,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??L$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let 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{...mJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mJ};return{...mJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Jf.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 A2(this.config.logDirectory,cB.F_OK|cB.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await J2(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:o0.from($);try{if(!c8(this.currentLogFile))await u8(this.currentLogFile,"",{mode:420});if(U=iB(this.currentLogFile,"a",420),w2(U,Z,{flag:"a"}),bB(U),U!==void 0)i8(U),U=void 0;if((await ew(this.currentLogFile)).size===0){if(await u8(this.currentLogFile,Z,{flag:"w",mode:420}),(await ew(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{i8(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 $1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return $1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return $1(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 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 b8(16).toString("hex")}generateKey(){return b8(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=b8(16),J=oG("aes-256-gcm",w,A),U=o0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:o0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=vB(),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(w$())return;let $=await ew(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 XJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await ew(A).catch(()=>null))try{if(await uB(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await _J(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 u8(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 ew(A).catch(()=>null))await uB(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await XJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await _J($1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=PB($),J=$2(w),U=vB();await U2(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()})),c8(this.currentLogFile))try{let $=iB(this.currentLogFile,"r+");bB($),i8($)}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 XJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await _J($1(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?l.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=L$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${l.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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 E=Vh[$],B=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",h;switch($){case"debug":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:l.gray(f),level:$}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:l.green(f),level:$}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h),W){let j=W.split(`
|
|
127
|
+
`}function S8(){return sw.randomBytes(20)}function IB($=2048){let{privateKey:w,publicKey:A}=sw.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function _G($){let w=$.export({type:"spki",format:"der"});return sw.createHash("sha1").update(w).digest()}function CB($){let w={serialNumber:$.serialNumber||S8(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:_G($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=VG(w),J=OG(A,$.signingKey);return{certificate:XG(J,"CERTIFICATE"),certificateDer:J}}function yB($){return $.export({type:"pkcs8",format:"pem"})}function DG($){return sw.createPrivateKey($)}function kG($){let w=new sw.X509Certificate($),A=w.publicKey,J=[],U=w.subject.split(`
|
|
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 V8($={}){M("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||B0.DEFAULT_KEY_SIZE;M("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:J}=IB(w),U=[{shortName:"C",value:$.countryName||J$.countryName},{shortName:"ST",value:$.stateName||J$.stateName},{shortName:"L",value:$.localityName||J$.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:Y,notAfter:f}=L8({validityYears:$.validityYears||B0.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=CB({serialNumber:S8(),notBefore:Y,notAfter:f,subject:U,publicKey:J,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:yB(A),notBefore:Y,notAfter:f}}async function O8($){if(M("ca","Generating new certificate",$.verbose),M("ca",`Options: ${VJ($)}`,$.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}=kG($.rootCA.certificate),A=DG($.rootCA.privateKey);M("ca",`Generating ${B0.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let J=B0.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:Y}=IB(J),f=$.commonName||qB($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||J$.countryName},{shortName:"ST",value:$.stateName||J$.stateName},{shortName:"L",value:$.localityName||J$.localityName},{shortName:"O",value:$.organizationName||J$.organizationName},{shortName:"CN",value:f}],{notBefore:Z,notAfter:E}=L8({validityDays:$.validityDays||B0.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),B=NB($),h=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},j=$.extKeyUsage||{serverAuth:!0},{certificate:F}=CB({serialNumber:S8(),notBefore:Z,notAfter:E,subject:W,issuer:w,publicKey:Y,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:h,extendedKeyUsage:j,subjectAltName:B});return{certificate:F,privateKey:yB(U),notBefore:Z,notAfter:E}}function LB($,w){M(I.STORAGE,`Storing certificate and private key with options: ${VJ(w)}`,w?.verbose);let{certPath:A,keyPath:J}=y8({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=z8.dirname(A);if(!k0.existsSync(U))M(I.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),k0.mkdirSync(U,{recursive:!0});M(I.STORAGE,"Writing certificate file",w?.verbose),k0.writeFileSync(A,$.certificate);let Y=z8.dirname(J);if(!k0.existsSync(Y))M(I.STORAGE,`Creating private key directory: ${Y}`,w?.verbose),k0.mkdirSync(Y,{recursive:!0});return M(I.STORAGE,"Writing private key file",w?.verbose),k0.writeFileSync(J,$.privateKey),M(I.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function SB($,w){M(I.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=y8({basePath:w?.basePath,caCertPath:w?.caCertPath});M(I.STORAGE,`CA certificate path: ${A}`,w?.verbose);let J=z8.dirname(A);if(!k0.existsSync(J))M(I.STORAGE,`Creating CA certificate directory: ${J}`,w?.verbose),k0.mkdirSync(J,{recursive:!0});return M(I.STORAGE,"Writing CA certificate file",w?.verbose),k0.writeFileSync(A,$),M(I.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function QG($,w){if(IJ.platform()!=="darwin")return!1;try{let A=DE(`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(DE("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 X8($,w,A){M(I.TRUST,`Adding certificate to system trust store with options: ${VJ(A)}`,A?.verbose),M(I.TRUST,"Storing certificate and private key",A?.verbose);let J=LB($,A);M(I.TRUST,"Storing CA certificate",A?.verbose);let U=SB(w,A),Y=IJ.platform();M(I.TRUST,`Detected platform: ${Y}`,A?.verbose);let f=iG[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 _N,FJ,H8,nH,mH=($)=>$,gH=($,w)=>{for(var A in w)nH($,A,{get:w[A],enumerable:!0,configurable:!0,set:dH.bind(w,A)})},lH=($,w)=>()=>($&&(w=$($=0)),w),bE,lE,rw,D1,tE,NT,RT,HE,UJ,J8,C$,g,KT,TE,MT,GE,IT,CT,rY,yT,qE,NE,aY,LT,ST,VT,OT,YJ,pE,XT,y$,_T,DT,RE,fJ,U8,h$,k,kT,KE,QT,ME,xT,PT,sY,bT,IE,CE,iT,oY,cT,uT,vT,nT,mT,ZJ,rE,dT,gT="0.15.6",d$,GJ,O1,Y8,f8,qJ,Z8,W8,X1,E8,B8,s0,aE,sE,E0,Q0,oE,eE,lT,pT,$B,NJ,AK,q$,P,JK,aT,UK,sT,YK,fK,yE,ZK,oT,eT,WK,LE,EK,BK,hK,FK,jK,eY,$G,zK,F0,AB,RJ,JB,UB,I8,YB,fB,KJ,ZB,WB,aw,ZG,O0,HK,TK,GK,HB,J$,B0,I,pw,FG,VE="[redacted]",jG,zG,h0,x$,xG,PG,bG,iG;var VB=X$(()=>{_N=$H(import.meta.url);FJ=new xE,H8=new PE,nH=Object.defineProperty;bE={};gH(bE,{withErrorRecovery:()=>uE,tryLoadConfig:()=>HT,loadConfigWithResult:()=>jT,loadConfig:()=>gE,isRetryableError:()=>ZT,isConfigNotFoundError:()=>fT,isBunfigError:()=>vE,globalPerformanceMonitor:()=>D1,globalCache:()=>rw,getEnvOrDefault:()=>WT,generateConfigTypes:()=>TT,defaultGeneratedDir:()=>eE,defaultConfigDir:()=>oE,deepMergeWithArrayStrategy:()=>R8,deepMerge:()=>nE,createLibraryConfig:()=>GT,config:()=>zT,bunfigPlugin:()=>qT,applyEnvVarsToConfig:()=>L1,TypeGenerationError:()=>W8,SchemaValidationError:()=>X1,PluginError:()=>B8,PerformanceMonitor:()=>G8,FileSystemError:()=>Z8,ErrorFactory:()=>s0,EnvVarError:()=>qJ,EnvProcessor:()=>yJ,ConfigValidator:()=>K8,ConfigValidationError:()=>Y8,ConfigNotFoundError:()=>GJ,ConfigMergeError:()=>f8,ConfigLoader:()=>M8,ConfigLoadError:()=>O1,ConfigFileLoader:()=>LJ,ConfigCache:()=>T8,CacheUtils:()=>tE,BunfigError:()=>d$,BrowserConfigError:()=>E8,ArrayMergeStrategies:()=>aE});lT=lH(async()=>{lE=import.meta.require,rw=new T8,D1=new G8,tE={createKey:tH,isEquivalent:pH,estimateMemoryUsage:rH},NT=BJ(w8.cwd(),"config"),RT=BJ(w8.cwd(),"src/generated"),HE=EJ.env.CLARITY_LOG_DIR||WH(oH(),"logs"),UJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:HE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},J8=await eH(),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"},g=C$,KT=C$.red,TE=C$.green,MT=C$.yellow,GE=C$.blue,IT=C$.magenta,CT=C$.cyan,rY=C$.white,yT=C$.gray,qE=C$.bgRed,NE=C$.bgYellow,aY=C$.bold,LT=C$.dim,ST=C$.italic,VT=C$.underline,OT=C$.reset,YJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pE={debug:"\uD83D\uDD0D",info:GE("ℹ"),success:TE("✓"),warning:NE(rY(aY(" WARN "))),error:qE(rY(aY(" ERROR ")))},XT=new zJ("stacks"),y$=new zJ("bunfig",{showTags:!0}),_T=k$(V1.cwd(),"config"),DT=k$(V1.cwd(),"src/generated"),RE=WJ.env.CLARITY_LOG_DIR||fH(JT(),"logs"),fJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:RE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},U8=await UT(),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"},k=h$,kT=h$.red,KE=h$.green,QT=h$.yellow,ME=h$.blue,xT=h$.magenta,PT=h$.cyan,sY=h$.white,bT=h$.gray,IE=h$.bgRed,CE=h$.bgYellow,iT=h$.bgGray,oY=h$.bold,cT=h$.dim,uT=h$.italic,vT=h$.underline,nT=h$.strikethrough,mT=h$.reset,ZJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rE={debug:"\uD83D\uDD0D",info:ME("ℹ"),success:KE("✓"),warning:CE(sY(oY(" WARN "))),error:IE(sY(oY(" ERROR ")))},dT=new TJ("stacks"),d$=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}${$}`}},GJ=class extends d${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})}},O1=class extends d${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}},Y8=class extends d${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},f8=class extends d${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}},qJ=class extends d${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})}},Z8=class extends d${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}},W8=class extends d${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}},X1=class extends d${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 d${code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}},B8=class extends d${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}},s0={configNotFound($,w,A){return new GJ($,w,A)},configLoad($,w,A){return new O1($,w,A)},configValidation($,w,A){return new Y8($,w,A)},configMerge($,w,A,J){return new f8($,w,A,J)},envVar($,w,A,J){return new qJ($,w,A,J)},fileSystem($,w,A){return new Z8($,w,A)},typeGeneration($,w,A){return new W8($,w,A)},schemaValidation($,w,A){return new X1($,w,A)},browserConfig($,w,A,J){return new E8($,w,A,J)},plugin($,w,A){return new B8($,w,A)}},aE={replace:"replace",concat:"concat",smart:"smart"},sE=/^https?:\/\//,E0=new TJ("bunfig",{showTags:!0}),Q0=new M8,oE=Q$(Zw.cwd(),"config"),eE=Q$(Zw.cwd(),"src/generated")});pT=hJ.env.CLARITY_LOG_DIR||XH(tT(),"logs"),$B={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:pT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},NJ={...$B},AK=(async()=>{try{let{loadConfig:$}=await lT().then(()=>bE),w=await $({name:"clarity",alias:"logging",defaultConfig:$B,cwd:hJ.cwd()});if(w)Object.assign(NJ,w)}catch{}return NJ})();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"},P=q$,JK=q$.red,aT=q$.green,UK=q$.yellow,sT=q$.blue,YK=q$.magenta,fK=q$.cyan,yE=q$.white,ZK=q$.gray,oT=q$.bgRed,eT=q$.bgYellow,WK=q$.bgGray,LE=q$.bold,EK=q$.dim,BK=q$.italic,hK=q$.underline,FK=q$.strikethrough,jK=q$.reset,eY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$G={debug:"\uD83D\uDD0D",info:sT("ℹ"),success:aT("✓"),warning:eT(yE(LE(" WARN "))),error:oT(yE(LE(" ERROR ")))};zK=new SJ("stacks");F0=class F0 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}${$}`}};AB=class AB extends F0{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 F0{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}};JB=class JB extends F0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};UB=class UB extends F0{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}};I8=class I8 extends F0{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})}};YB=class YB extends F0{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}};fB=class fB extends F0{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}};KJ=class KJ extends F0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};ZB=class ZB extends F0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,J){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:J})}};WB=class WB extends F0{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}};aw={configNotFound($,w,A){return new AB($,w,A)},configLoad($,w,A){return new RJ($,w,A)},configValidation($,w,A){return new JB($,w,A)},configMerge($,w,A,J){return new UB($,w,A,J)},envVar($,w,A,J){return new I8($,w,A,J)},fileSystem($,w,A){return new YB($,w,A)},typeGeneration($,w,A){return new fB($,w,A)},schemaValidation($,w,A){return new KJ($,w,A)},browserConfig($,w,A,J){return new ZB($,w,A,J)},plugin($,w,A){return new WB($,w,A)}};ZG=/^https?:\/\//;O0=new SJ("bunfig",{showTags:!0});HK=new zB;TK=e$(CJ.cwd(),"config"),GK=e$(CJ.cwd(),"src/generated"),HB={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:QY.join(kY.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:QY.join(kY.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:QY.join(kY.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},J$=HB,B0={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"},pw={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};FG=hG(EG);jG=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),zG=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;h0={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"};xG={platform:"darwin",async addCertificate($,w){if(await QG($,w?.verbose)){M(I.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),pw.success("Certificate is already trusted in system keychain");return}M(I.TRUST,"Adding certificate to macOS keychain",w?.verbose),await a0(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let J=A||J$.commonName;M(I.TRUST,`Removing certificate ${J} from macOS keychain`,w?.verbose);try{await a0(`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}}},PG={platform:"win32",async addCertificate($,w){M(I.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await a0(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let J=A||J$.commonName;M(I.TRUST,`Removing certificate ${J} from Windows certificate store`,w?.verbose);try{await a0(`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}}},bG={platform:"linux",async addCertificate($,w){M(I.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=IJ.homedir(),J=B0.LINUX_CERT_DB_FILENAME,U=B0.LINUX_TRUST_ARGS;M(I.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let Y=F8(A,J);if(Y.length===0){pw.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 ${J$.commonName}`,w?.verbose),await a0(`certutil -d sql:${f} -D -n ${J$.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 a0(`certutil -d sql:${f} -A -t ${U} -n ${J$.commonName} -i ${$}`),pw.info(`Cert added to ${f}`)}},async removeCertificate($,w,A){let J=A||J$.commonName;M(I.TRUST,`Removing certificate ${J} from Linux certificate store`,w?.verbose);let U=IJ.homedir(),Y=B0.LINUX_CERT_DB_FILENAME;M(I.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let f=F8(U,Y);if(f.length===0){pw.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 a0(`certutil -d sql:${W} -D -n "${J}"`),pw.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}`)}}}},iG={darwin:xG,win32:PG,linux:bG}});var OB=X$(()=>{VB()});import{homedir as _8}from"node:os";import{join as D8,resolve as fM}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",cG,k8;var Q8=X$(()=>{XY();cG={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:D8(_8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:D8(_8(),".stacks","ssl","stacks.localhost.crt"),keyPath:D8(_8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},k8=cG});import{execSync as uG}from"node:child_process";function XB($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function OJ($){try{let w=uG(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return XB(w)}catch{return null}}var x8=()=>{};import{existsSync as _B,statSync as DB}from"fs";import{existsSync as $f,mkdirSync as lG,readdirSync as tG,writeFileSync as pG}from"fs";import{homedir as ow}from"os";import{dirname as kB,resolve as b$}from"path";import Ww from"process";import{join as rG,relative as aG,resolve as QB}from"path";import lJ from"process";import{existsSync as Th,mkdirSync as NM,readdirSync as RM,writeFileSync as KM}from"fs";import{homedir as P8}from"os";import{dirname as CM,resolve as P$}from"path";import Q1 from"process";import{join as sG,relative as oG,resolve as xB}from"path";import tJ from"process";import{existsSync as Gh,mkdirSync as OM,readdirSync as XM,writeFileSync as _M}from"fs";import{dirname as kM,resolve as pJ}from"path";import wf from"process";import{Buffer as o0}from"buffer";import{createCipheriv as eG,createDecipheriv as $2,randomBytes as b8}from"crypto";import{closeSync as i8,createReadStream as PB,createWriteStream as w2,existsSync as c8,fsyncSync as bB,openSync as iB,writeFileSync as A2}from"fs";import{access as J2,constants as cB,mkdir as U2,readdir as XJ,rename as uB,stat as ew,unlink as _J,writeFile as u8}from"fs/promises";import{join as $1}from"path";import L$ from"process";import{pipeline as Y2}from"stream/promises";import{createGzip as vB}from"zlib";import w1 from"process";import b0 from"process";import{Buffer as x0}from"buffer";import{createCipheriv as f2,createDecipheriv as Z2,randomBytes as v8}from"crypto";import{closeSync as n8,createReadStream as nB,createWriteStream as W2,existsSync as DJ,fsyncSync as mB,openSync as dB,writeFileSync as E2}from"fs";import{access as B2,constants as gB,mkdir as h2,readdir as kJ,rename as lB,stat as A1,unlink as QJ,writeFile as m8}from"fs/promises";import{isAbsolute as F2,join as J1,resolve as j2}from"path";import X from"process";import{pipeline as z2}from"stream/promises";import{createGzip as tB}from"zlib";import U1 from"process";import i0 from"process";import xJ from"process";import{existsSync as PJ}from"fs";import{resolve as d8}from"path";import{existsSync as H2}from"fs";import{existsSync as T2,readdirSync as G2}from"fs";import{extname as g8,resolve as pB}from"path";import q2 from"process";import{join as N7,relative as R7,resolve as fh}from"path";import wU from"process";import{Buffer as P0}from"buffer";import{createCipheriv as I7,createDecipheriv as C7,randomBytes as a8}from"crypto";import{closeSync as s8,createReadStream as Zh,createWriteStream as y7,existsSync as iJ,fsyncSync as Wh,openSync as Eh,writeFileSync as L7}from"fs";import{access as S7,constants as Bh,mkdir as V7,readdir as cJ,rename as hh,stat as Y1,unlink as uJ,writeFile as o8}from"fs/promises";import{isAbsolute as O7,join as f1,resolve as X7}from"path";import _ from"process";import{pipeline as _7}from"stream/promises";import{createGzip as Fh}from"zlib";import Z1 from"process";import c0 from"process";function mG($,w){this[$]=nG.bind(null,w)}class hf{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(!_B($))return!0;return DB($).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=_B(A)?DB(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 Ff{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 N2($,w={}){let J=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return J?`${$}:${J}`:$}function R2($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function K2($){return $.getStats().size*2}function jf($,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((f)=>a(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(a(U)&&"path"in U){if(!J.find((f)=>a(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>rJ(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]=jf(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((Z)=>a(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(a(f)&&"path"in f){if(!Y.find((Z)=>a(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>rJ(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 rJ($,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(!rJ($[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(!rJ($[U],w[U]))return!1}return!0}return!1}function a($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function M2($,w){if(!Gh($))return null;try{let A=await import($),J=A.default||A;if(typeof J!=="object"||J===null||Array.isArray(J))return null;try{return jf(w,J)}catch{return null}}catch{return null}}async function I2({name:$="",cwd:w,defaultConfig:A}){let J=w||wf.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],Y=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let f of Y)for(let W of U){let Z=pJ(J,`${f}${W}`),E=await M2(Z,A);if(E!==null)return E}try{let f=pJ(J,"package.json");if(Gh(f)){let Z=(await import(f))[$];if(Z&&typeof Z==="object"&&!Array.isArray(Z))try{return jf(A,Z)}catch{}}}catch{}return A}function C2($,w={}){let A=tJ.cwd();while(A.includes("storage"))A=xB(A,"..");let J=xB(A,$||"");if(w?.relative)return oG(tJ.cwd(),J);return J}async function y2(){try{let $=await I2({name:"clarity",defaultConfig:nJ,cwd:tJ.cwd(),endpoint:"",headers:{}});return{...nJ,...$}}catch{return nJ}}function w$(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function L2(){if(b0.env.NODE_ENV==="test"||b0.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b0<"u"){let $=b0.type;if($==="renderer"||$==="worker")return!1;return!!(b0.versions&&(b0.versions.node||b0.versions.bun))}return!1}class qh{async format($){let w=await L2(),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:w1.pid,hostname:w(),environment:w1.env.NODE_ENV||"development",platform:w1.platform,version:w1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:w1.env.NODE_ENV||w1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class aJ{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={...Jf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new qh,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??L$.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let 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{...mJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mJ};return{...mJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Jf.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 J2(this.config.logDirectory,cB.F_OK|cB.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await U2(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:o0.from($);try{if(!c8(this.currentLogFile))await u8(this.currentLogFile,"",{mode:420});if(U=iB(this.currentLogFile,"a",420),A2(U,Z,{flag:"a"}),bB(U),U!==void 0)i8(U),U=void 0;if((await ew(this.currentLogFile)).size===0){if(await u8(this.currentLogFile,Z,{flag:"w",mode:420}),(await ew(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{i8(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 $1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return $1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return $1(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 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 b8(16).toString("hex")}generateKey(){return b8(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=b8(16),J=eG("aes-256-gcm",w,A),U=o0.concat([J.update($,"utf8"),J.final()]),Y=J.getAuthTag();return{encrypted:o0.concat([A,U,Y]),iv:A}}async compressData($){return new Promise((w,A)=>{let J=vB(),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(w$())return;let $=await ew(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 XJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await ew(A).catch(()=>null))try{if(await uB(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await _J(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 u8(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 ew(A).catch(()=>null))await uB(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await XJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await _J($1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=PB($),J=w2(w),U=vB();await Y2(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()})),c8(this.currentLogFile))try{let $=iB(this.currentLogFile,"r+");bB($),i8($)}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 XJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await _J($1(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?l.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=L$.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${l.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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 E=Vh[$],B=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",h;switch($){case"debug":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:l.gray(f),level:$}),console.error(h);break;case"info":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h);break;case"success":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:l.green(f),level:$}),console.error(h);break;case"warning":h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.warn(h);break;case"error":if(h=this.formatConsoleMessage({timestamp:U,icon:E,tag:B,message:f,level:$}),console.error(h),W){let j=W.split(`
|
|
129
129
|
`);for(let F of j)if(F.trim()&&!F.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:l.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!w$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}if(!this.shouldLog($))return;let Z=`${Y} ${this.environment}.${$.toUpperCase()}: ${f}
|
|
130
130
|
`;if(W)Z+=`${W}
|
|
131
131
|
`;Z=Z.replace(this.ANSI_PATTERN,""),await this.writeToFile(Z)}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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
132
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!w$()){let B=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:l.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!w$())console.error(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 aJ(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(!c8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return PB(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=o0.isBuffer($)?$:o0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W
|
|
132
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.fancy&&!w$()){let B=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:l.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!w$())console.error(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 aJ(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(!c8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return PB(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=o0.isBuffer($)?$:o0.from($,"base64"),U=J.slice(0,16),Y=J.slice(-16),f=J.slice(16,-16),W=$2("aes-256-gcm",A,U);return W.setAuthTag(Y),o0.concat([W.update(f),W.final()]).toString("utf8")}catch(J){throw Error(`Decryption failed: ${J instanceof Error?J.message:String(J)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return w$()}isServerMode(){return!w$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w);if(this.fancy&&!w$()){let Y=$.split(`
|
|
133
133
|
`),f=Math.max(...Y.map((B)=>B.length))+2,W=`┌${"─".repeat(f)}┐`,Z=`└${"─".repeat(f)}┘`,E=Y.map((B)=>{let h=" ".repeat(f-B.length-2);return`│ ${B}${h} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:A,message:l.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(W)})),E.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:l.cyan(Z),showTimestamp:!1}))}else if(!w$())console.error(`${J} ${this.environment}.INFO: [BOX] ${$}`);let U=`${J} ${this.environment}.INFO: [BOX] ${$}
|
|
134
134
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(w$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${l.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();L$.stdin.removeListener("data",A);try{if(typeof L$.stdin.setRawMode==="function")L$.stdin.setRawMode(!1)}catch{}L$.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof L$.stdin.setRawMode==="function")L$.stdin.setRawMode(!0)}catch{}L$.stdin.resume(),L$.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,W=0;if(A=$.replace(f,(Z,E)=>{if(E==="%")return"%";if(W>=w.length)return Z;let B=w[W++];switch(E){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 Z}}),W<w.length)A+=` ${w.slice(W).map((Z)=>typeof Z==="object"?JSON.stringify(Z,null,2):String(Z)).join(" ")}`}if(this.fancy&&!w$()){let f=this.options.showTags!==!1&&this.name?l.gray(this.formatTag(this.name)):"",W=l.blue("◐");console.error(`${W} ${f} ${l.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
|
|
135
135
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}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:(f,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w$())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,f)),W!==void 0)this.activeProgressBar.message=W;let Z=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Z)},finish:(f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w$())return;if(this.activeProgressBar.current=this.activeProgressBar.total,f!==void 0)this.activeProgressBar.message=f;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(f,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||w$())return;L$.stdout.write(`${"\r".padEnd(L$.stdout.columns||80)}\r`),this.log(W,f),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||w$()||!L$.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=l.green("━".repeat(J)),f=l.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=w||A===100?l.green("✓"):l.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${l.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=L$.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,L$.stdout.write($.lastRenderedLine),w)L$.stdout.write(`
|
|
136
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||w$()||!L$.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 XJ(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=$1(this.config.logDirectory,J);if($.before)try{if((await ew(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 _J(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 vJ($,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((f)=>m(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(m(U)&&"path"in U){if(!J.find((f)=>m(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>sJ(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]=vJ(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((Z)=>m(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(m(f)&&"path"in f){if(!Y.find((Z)=>m(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>sJ(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 zf($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:vJ($,w);if(Array.isArray($))return A==="replace"?w:vJ($,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]=vJ(f,Y);else if(m(Y)&&m(f))J[U]=zf(f,Y,A);else J[U]=Y}return J}function sJ($,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(!sJ($[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(!sJ($[U],w[U]))return!1}return!0}return!1}function m($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function bJ($,w,A="replace"){if(!Th($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return zf(w,U,A)}catch{return null}}catch{return null}}function L2($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${J}_${h.map(j).join("_")}`,T=`${J}_${h.map((H)=>H.toUpperCase()).join("_")}`;if(A)V$.info(`Checking environment variable ${F} for config ${$}.${h.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))Z[E]=Y(B,h);else{let H=Q1.env[F]||Q1.env[T];if(H!==void 0){if(A)V$.info(`Using environment variable ${H?F:T} for config ${$}.${h.join(".")}`);if(typeof B==="number")Z[E]=Number(H);else if(typeof B==="boolean")Z[E]=H.toLowerCase()==="true";else if(Array.isArray(B))try{let G=JSON.parse(H);if(Array.isArray(G))Z[E]=G;else Z[E]=H.split(",").map((q)=>q.trim())}catch{Z[E]=H.split(",").map((G)=>G.trim())}else Z[E]=H}}}return Z}return Y(U)}async function S2({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)?L2($,U,Y):U,E=A||Q1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(Y)V$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let h=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,P$(E,"config"),P$(E,".config"),J?P$(E,J):void 0].filter(Boolean)));for(let G of H){if(Y)V$.info(`Searching for configuration in: ${G}`);let N=[P$(E,"config"),P$(E,".config")].concat(J?[P$(E,J)]:[]).includes(G)?[...h,...j,...F,...T]:[...j,...h,...T,...F];for(let K of N)for(let C of B){let y=P$(G,`${K}${C}`),S=await bJ(y,Z,W);if(S!==null){if(Y)V$.success(`Configuration loaded from: ${y}`);return S}}}if($){let G=P$(P8(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)V$.info(`Checking user config directory: ${G}`);for(let N of q)for(let K of B){let C=P$(G,`${N}${K}`),y=await bJ(C,Z,W);if(y!==null){if(Y)V$.success(`Configuration loaded from user config directory: ${C}`);return y}}}if($){let G=P$(P8(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)V$.info(`Checking user config directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=P$(G,`${N}${K}`),y=await bJ(C,Z,W);if(y!==null){if(Y)V$.success(`Configuration loaded from user config directory dotfile: ${C}`);return y}}}if($){let G=P8(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)V$.info(`Checking user home directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=P$(G,`${N}${K}`),y=await bJ(C,Z,W);if(y!==null){if(Y)V$.success(`Configuration loaded from user home directory: ${C}`);return y}}}try{let G=P$(E,"package.json");if(Th(G)){let q=await import(G),N=q[$];if(!N&&w){if(N=q[w],N&&Y)V$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)V$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return zf(Z,N,W)}catch(K){if(Y)V$.warn("Failed to merge package.json config:",K)}}}catch(G){if(Y)V$.warn("Failed to load package.json:",G)}if(Y)V$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function V2($,w={}){let A=lJ.cwd();while(A.includes("storage"))A=QB(A,"..");let J=QB(A,$||"");if(w?.relative)return rG(lJ.cwd(),J);return J}async function O2(){try{let $=await S2({name:"clarity",alias:"logging",defaultConfig:dJ,cwd:lJ.cwd()});return{...dJ,...$||{}}}catch{return dJ}}function j$(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function X2(){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 Nh{async format($){let w=await X2(),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:U1.pid,hostname:w(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oJ{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={...Uf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Nh,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{...gJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...gJ};return{...gJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Uf.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 E2(this.config.logDirectory,gB.F_OK|gB.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await B2(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x0.from($);try{if(!DJ(this.currentLogFile))await m8(this.currentLogFile,"",{mode:420});if(U=dB(this.currentLogFile,"a",420),W2(U,Z,{flag:"a"}),mB(U),U!==void 0)n8(U),U=void 0;if((await A1(this.currentLogFile)).size===0){if(await m8(this.currentLogFile,Z,{flag:"w",mode:420}),(await A1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{n8(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 J1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return J1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return J1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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 v8(16).toString("hex")}generateKey(){return v8(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=v8(16),J=Y2("aes-256-gcm",w,A),U=x0.isBuffer($)?$:x0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),E=x0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=tB(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(x0.from(x0.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 A1(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 kJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await A1(A).catch(()=>null))try{if(await lB(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await QJ(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 m8(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 A1(A).catch(()=>null))await lB(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await kJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await QJ(J1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=nB($),J=Z2(w),U=tB();await j2(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()})),DJ(this.currentLogFile))try{let $=dB(this.currentLogFile,"r+");mB($),n8($)}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 kJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await QJ(J1(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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=X.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${Q.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(h2(w)||w.startsWith("./")||w.startsWith("../"))w=F2(w);else return null;return DJ(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":Oh[$],j=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Q.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Q.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
136
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||w$()||!L$.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 XJ(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=$1(this.config.logDirectory,J);if($.before)try{if((await ew(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 _J(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 vJ($,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((f)=>m(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(m(U)&&"path"in U){if(!J.find((f)=>m(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((Y)=>sJ(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]=vJ(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((Z)=>m(Z)&&("name"in Z)&&Z.name===f.name))Y.push(f)}else if(m(f)&&"path"in f){if(!Y.find((Z)=>m(Z)&&("path"in Z)&&Z.path===f.path))Y.push(f)}else if(!Y.some((W)=>sJ(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 zf($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:vJ($,w);if(Array.isArray($))return A==="replace"?w:vJ($,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]=vJ(f,Y);else if(m(Y)&&m(f))J[U]=zf(f,Y,A);else J[U]=Y}return J}function sJ($,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(!sJ($[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(!sJ($[U],w[U]))return!1}return!0}return!1}function m($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function bJ($,w,A="replace"){if(!Th($))return null;try{let J=await import($),U=J.default||J;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return zf(w,U,A)}catch{return null}}catch{return null}}function S2($,w,A=!1){if(!$)return w;let J=$.toUpperCase().replace(/-/g,"_"),U={...w};function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=(H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${J}_${h.map(j).join("_")}`,T=`${J}_${h.map((H)=>H.toUpperCase()).join("_")}`;if(A)V$.info(`Checking environment variable ${F} for config ${$}.${h.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))Z[E]=Y(B,h);else{let H=Q1.env[F]||Q1.env[T];if(H!==void 0){if(A)V$.info(`Using environment variable ${H?F:T} for config ${$}.${h.join(".")}`);if(typeof B==="number")Z[E]=Number(H);else if(typeof B==="boolean")Z[E]=H.toLowerCase()==="true";else if(Array.isArray(B))try{let G=JSON.parse(H);if(Array.isArray(G))Z[E]=G;else Z[E]=H.split(",").map((q)=>q.trim())}catch{Z[E]=H.split(",").map((G)=>G.trim())}else Z[E]=H}}}return Z}return Y(U)}async function V2({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)?S2($,U,Y):U,E=A||Q1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(Y)V$.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${E}`);let h=[$,`.${$}`].filter(Boolean),j=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],H=Array.from(new Set([E,P$(E,"config"),P$(E,".config"),J?P$(E,J):void 0].filter(Boolean)));for(let G of H){if(Y)V$.info(`Searching for configuration in: ${G}`);let N=[P$(E,"config"),P$(E,".config")].concat(J?[P$(E,J)]:[]).includes(G)?[...h,...j,...F,...T]:[...j,...h,...T,...F];for(let K of N)for(let C of B){let y=P$(G,`${K}${C}`),S=await bJ(y,Z,W);if(S!==null){if(Y)V$.success(`Configuration loaded from: ${y}`);return S}}}if($){let G=P$(P8(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(Y)V$.info(`Checking user config directory: ${G}`);for(let N of q)for(let K of B){let C=P$(G,`${N}${K}`),y=await bJ(C,Z,W);if(y!==null){if(Y)V$.success(`Configuration loaded from user config directory: ${C}`);return y}}}if($){let G=P$(P8(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(Y)V$.info(`Checking user config directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=P$(G,`${N}${K}`),y=await bJ(C,Z,W);if(y!==null){if(Y)V$.success(`Configuration loaded from user config directory dotfile: ${C}`);return y}}}if($){let G=P8(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(Y)V$.info(`Checking user home directory for dotfile configs: ${G}`);for(let N of q)for(let K of B){let C=P$(G,`${N}${K}`),y=await bJ(C,Z,W);if(y!==null){if(Y)V$.success(`Configuration loaded from user home directory: ${C}`);return y}}}try{let G=P$(E,"package.json");if(Th(G)){let q=await import(G),N=q[$];if(!N&&w){if(N=q[w],N&&Y)V$.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(Y)V$.success(`Configuration loaded from package.json: ${N===q[$]?$:w}`);return zf(Z,N,W)}catch(K){if(Y)V$.warn("Failed to merge package.json config:",K)}}}catch(G){if(Y)V$.warn("Failed to load package.json:",G)}if(Y)V$.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return Z}function O2($,w={}){let A=lJ.cwd();while(A.includes("storage"))A=QB(A,"..");let J=QB(A,$||"");if(w?.relative)return aG(lJ.cwd(),J);return J}async function X2(){try{let $=await V2({name:"clarity",alias:"logging",defaultConfig:dJ,cwd:lJ.cwd()});return{...dJ,...$||{}}}catch{return dJ}}function j$(){if(i0.env.NODE_ENV==="test"||i0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _2(){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 Nh{async format($){let w=await _2(),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:U1.pid,hostname:w(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oJ{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={...Uf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Nh,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{...gJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...gJ};return{...gJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Uf.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 B2(this.config.logDirectory,gB.F_OK|gB.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await h2(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x0.from($);try{if(!DJ(this.currentLogFile))await m8(this.currentLogFile,"",{mode:420});if(U=dB(this.currentLogFile,"a",420),E2(U,Z,{flag:"a"}),mB(U),U!==void 0)n8(U),U=void 0;if((await A1(this.currentLogFile)).size===0){if(await m8(this.currentLogFile,Z,{flag:"w",mode:420}),(await A1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{n8(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 J1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return J1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return J1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(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 v8(16).toString("hex")}generateKey(){return v8(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=v8(16),J=f2("aes-256-gcm",w,A),U=x0.isBuffer($)?$:x0.from($,"utf8"),Y=J.update(U),f=J.final(),W=Y.length+f.length,Z=J.getAuthTag(),E=x0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=tB(),U=[];J.on("data",(Y)=>U.push(Y)),J.on("end",()=>w(x0.from(x0.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 A1(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 kJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await A1(A).catch(()=>null))try{if(await lB(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await QJ(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 m8(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 A1(A).catch(()=>null))await lB(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await kJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await QJ(J1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=nB($),J=W2(w),U=tB();await z2(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()})),DJ(this.currentLogFile))try{let $=dB(this.currentLogFile,"r+");mB($),n8($)}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 kJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await QJ(J1(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=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=X.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${Q.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(F2(w)||w.startsWith("./")||w.startsWith("../"))w=j2(w);else return null;return DJ(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":Oh[$],j=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Q.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Q.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
137
137
|
`);for(let H of T)if(H.trim()&&!H.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:Q.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!j$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}if(!this.shouldLog($))return;let B=`${Y} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
138
138
|
`;if(W)B+=`${W}
|
|
139
139
|
`;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,w=""){let A={update:(W,Z)=>{},finish:(W)=>{},interrupt:(W,Z)=>{}};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()&&!j$()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Z!==void 0)this.activeProgressBar.message=Z;if(this.shouldStyleConsole()&&!j$()&&X.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Z="info")=>{if(!j$()&&X.stdout.isTTY)X.stdout.write(`
|
|
140
140
|
`);if(this[Z==="warning"?"warn":Z](W),this.activeProgressBar&&this.shouldStyleConsole()&&!j$()&&X.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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
141
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!j$())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 oJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(j$())throw Error("createReadStream is not supported in browser environments");if(!DJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return nB(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=x0.isBuffer($)?$:x0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=
|
|
141
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!j$())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 oJ(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(j$())throw Error("createReadStream is not supported in browser environments");if(!DJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return nB(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=x0.isBuffer($)?$:x0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=Z2("aes-256-gcm",A,U);W.setAuthTag(Y);let Z=W.update(f),E=W.final(),B=Z.length+E.length,h=x0.allocUnsafe(B);return Z.copy(h,0),E.copy(h,Z.length),h.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 j$()}isServerMode(){return!j$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
142
142
|
`),Z=Math.max(...W.map((j)=>j.length))+2,E=`┌${"─".repeat(Z)}┐`,B=`└${"─".repeat(Z)}┘`,h=W.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:Q.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(E),showTimestamp:!1})),h.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:Q.cyan(B),showTimestamp:!1}))}else if(!j$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
143
143
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(j$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${Q.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=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(U==="y"||U==="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 Z=/%([sdijfo%])/g,E=0;if(A=$.replace(Z,(B,h)=>{if(h==="%")return"%";if(E>=w.length)return B;let j=w[E++];switch(h){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 B}}),E<w.length)A+=` ${w.slice(E).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${E}${Z} ${Q.cyan(J)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
144
144
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}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),U=$.barLength-J,Y=Q.green("━".repeat(J)),f=Q.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":w||A===100?Q.green("✓"):Q.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=X.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,X.stdout.write($.lastRenderedLine),w)X.stdout.write(`
|
|
145
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||j$()||!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(j$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await kJ(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=J1(this.config.logDirectory,J);if($.before)try{if((await A1(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 QJ(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)}}}async function Rh($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function Kh($){return $ instanceof
|
|
145
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||j$()||!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(j$()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await kJ(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=J1(this.config.logDirectory,J);if($.before)try{if((await A1(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 QJ(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)}}}async function Rh($,w={}){let{maxRetries:A=3,retryDelay:J=1000,isRetryable:U=()=>!0,fallback:Y}=w,f=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(Z){if(f=Z instanceof Error?Z:Error(String(Z)),W===A||!U(f))break;if(J>0)await new Promise((E)=>setTimeout(E,J))}if(Y!==void 0)return Y;throw f instanceof Error?f:Error(`Unknown error: ${String(f)}`)}function Kh($){return $ instanceof t$}function D2($){return $ instanceof eJ}function k2($){if(Kh($))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 JU{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:U=!0,useBackwardCompatibility:Y=!0,customParsers:f={},verbose:W=!1,trackPerformance:Z=!0}=A,E=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let B=J||this.generateEnvPrefix($),h={...w};return this.processObject(h,[],B,{useCamelCase:U,useBackwardCompatibility:Y,customParsers:f,verbose:W,configName:$}),{config:h,source:{type:"environment",priority:50,timestamp:new Date}}};if(Z)return b1.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[U,Y]of Object.entries($)){let f=[...w,U],W=f.map((B)=>this.formatEnvKey(B,J.useCamelCase)),Z=`${A}_${W.join("_")}`,E=J.useBackwardCompatibility?`${A}_${f.map((B)=>B.toUpperCase()).join("_")}`:null;if(J.verbose);if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.processObject(Y,f,A,J);else{let B=xJ.env[Z]||(E?xJ.env[E]:void 0);if(B!==void 0){if(J.verbose){let h=xJ.env[Z]?Z:E}try{$[U]=this.parseEnvironmentValue(B,typeof Y,Z,J.customParsers,J.configName)}catch(h){if(h instanceof $U)throw h;throw e0.envVar(Z,B,typeof Y,J.configName)}}}}}parseEnvironmentValue($,w,A,J,U){for(let[Y,f]of Object.entries(J))try{return f($)}catch{continue}for(let Y of this.defaultParsers)if(Y.canParse($,w))try{return Y.parse($)}catch{throw e0.envVar(A,$,`${w} (via ${Y.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[J,U]of Object.entries(xJ.env))if(J.startsWith(A)&&U!==void 0)w[J]=U;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(U){J.push(`Cannot parse value "${w}" as ${A}: ${U}`)}return{isValid:J.length===0,errors:J}}generateEnvVarDocs($,w,A={}){let{prefix:J,format:U="text"}=A,Y=J||this.generateEnvPrefix($),f=[];switch(this.extractEnvVarInfo(w,[],Y,f),U){case"markdown":return this.formatAsMarkdown(f,$);case"json":return JSON.stringify(f,null,2);default:return this.formatAsText(f,$)}}extractEnvVarInfo($,w,A,J){for(let[U,Y]of Object.entries($)){let f=[...w,U],W=`${A}_${f.map((Z)=>this.formatEnvKey(Z,!0)).join("_")}`;if(typeof Y==="object"&&Y!==null&&!Array.isArray(Y))this.extractEnvVarInfo(Y,f,A,J);else J.push({key:W,type:Array.isArray(Y)?"array":typeof Y,description:`Configuration for ${f.join(".")}`,example:this.generateExample(Y)})}}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,27 +154,27 @@ ${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 k2($,w){let A=Lh("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function Mh($,w,A={}){return Ih($,w,A,new WeakMap)}function Ih($,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 Ch($,w,U,J);if(!A0(w)||!A0($))return w;return b2($,w,A,J)}function Ch($,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 Q2($,w);case"smart":return x2($,w,J);default:return w}return w}function Q2($,w){let A=[...w];for(let J of $)if(!A.some((U)=>Af(U,J)))A.push(J);return A}function x2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(A0(w[0])&&A0($[0]))return P2($,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 P2($,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((E)=>A0(E)&&(W in E)&&E[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function b2($,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]=Ih(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=Ch(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function Hf($,w,A="replace"){return Mh($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function Af($,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(!Af($[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(!Af($[U],w[U]))return!1}return!0}return!1}function A0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class UU{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 E=W1.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!PJ($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new x1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new x1($,Error("Configuration must export a valid object"),"unknown");let G={config:Hf(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)W1.setWithFileCheck("file",G,$,Y);return G}catch(E){throw E instanceof Error?e0.configLoad($,E):e0.configLoad($,Error(String(E)))}};if(f)return b1.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(d8(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 Rh(async()=>{return PJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!PJ($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=d8($,`${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=d8($,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(!PJ($))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 Tf{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await b1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!z2(w))throw new P1(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 P1(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:_h},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Gf{fileLoader=new UU;envProcessor=new JU;validator=new Tf;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)j0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw j0.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:E="replace",verbose:B=!1}=$,h=Y||Ww.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(b$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw e0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),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 E=W?k1($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)j0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)j0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?k1($,A,U):A,W=[b$(ow(),".config",$),b$(ow(),".config"),ow()];for(let Z of W){if(U)j0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)j0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?k1($,J,Y):J;try{let Z=b$(A,"package.json");if(!$f(Z))return null;let E=await import(Z),B=E[$],h=$;if(!B&&w)B=E[w],h=w;if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)j0.success(`Configuration loaded from package.json: ${h}`);return{config:Hf(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)j0.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:k1($,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 e0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return W1.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);W1.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$(ow(),".config",$),b$(ow(),".config"),ow()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function rB($){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 i2($){return u0.loadConfig({...$,__strictErrorHandling:!0})}async function yh($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await u0.loadConfig($);else J=await u0.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)j0.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 u0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function c2($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await u0.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"&&rB(A)))return(await u0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await u0.loadConfig({...$,cwd:$.cwd||Ww.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&rB(w)))return(await u0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function u2($,w,A="replace"){let J=new UU;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function k1($,w,A=!1){let J=new JU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=Ww.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function v2($){let w=b$(Ww.cwd(),$.configDir),A=b$(Ww.cwd(),$.generatedDir),J=b$(A,"config-types.ts");if(!$f(kB(J)))gG(kB(J),{recursive:!0,mode:511});let U=$f(w)?lG(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${T7}
|
|
157
|
+
`;return A}}function Q2($,w){let A=Lh("process");if(typeof A>"u"||!A.env)return w;let J=A.env[$];return J!==void 0?J:w}function Mh($,w,A={}){return Ih($,w,A,new WeakMap)}function Ih($,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 Ch($,w,U,J);if(!A0(w)||!A0($))return w;return i2($,w,A,J)}function Ch($,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 x2($,w);case"smart":return P2($,w,J);default:return w}return w}function x2($,w){let A=[...w];for(let J of $)if(!A.some((U)=>Af(U,J)))A.push(J);return A}function P2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(A0(w[0])&&A0($[0]))return b2($,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 b2($,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((E)=>A0(E)&&(W in E)&&E[W]===U[W])){f=!0;break}}if(!f)J.push(U)}return J}function i2($,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]=Ih(Z,W,A,J);else if(Array.isArray(W)||Array.isArray(Z))Y[f]=Ch(Z,W,A.arrayMergeMode||"smart",J);else Y[f]=W}return Y}function Hf($,w,A="replace"){return Mh($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function Af($,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(!Af($[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(!Af($[U],w[U]))return!1}return!0}return!1}function A0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class UU{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 E=W1.getWithFileCheck("file",$);if(E){if(W)console.log(`Configuration loaded from cache: ${$}`);return E}}let Z=async()=>{if(!PJ($))return null;try{let E=`?t=${Date.now()}`,B=await import($+E),h=B.default||B,j="default"in B,F=Object.keys(B).length>0;if(!j&&!F)throw new x1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof h!=="object"||h===null||Array.isArray(h))throw new x1($,Error("Configuration must export a valid object"),"unknown");let G={config:Hf(w,h,J),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)W1.setWithFileCheck("file",G,$,Y);return G}catch(E){throw E instanceof Error?e0.configLoad($,E):e0.configLoad($,Error(String(E)))}};if(f)return b1.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(d8(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 Rh(async()=>{return PJ($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let J=[];if(!PJ($))return J;if(w||A){let U=this.generateNamePatterns(w||"",A);for(let Y of U)for(let f of this.extensions){let W=d8($,`${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=d8($,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(!PJ($))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 Tf{async validateConfiguration($,w,A={}){let{stopOnFirstError:J=!1,validateRequired:U=!0,validateTypes:Y=!0,customRules:f=[],trackPerformance:W=!0,verbose:Z=!1}=A,E=async()=>{let B=[],h=[],j={stopOnFirstError:J,validateRequired:U,validateTypes:Y,customRules:f,trackPerformance:W,verbose:Z};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,j);else if(Array.isArray(w))return this.validateWithRules($,[...w,...f],j);else return this.validateWithJSONSchema($,w,j)}catch(F){return B.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:B,warnings:h}}};if(W)return await b1.track("validateConfiguration",E);return E()}async validateWithSchemaFile($,w,A){try{if(!H2(w))throw new P1(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 P1(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 E=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(f[W],Z,E,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:_h},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Gf{fileLoader=new UU;envProcessor=new JU;validator=new Tf;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 E=f.__strictErrorHandling;if(Z instanceof Error&&Z.name==="ConfigNotFoundError"){if(E)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 B=Z.message.includes("EACCES")||Z.message.includes("EPERM")||Z.message.includes("permission denied"),h=!B&&(Z.message.includes("syntax")||Z.message.includes("Expected")||Z.message.includes("Unexpected")||Z.message.includes("BuildMessage")||Z.message.includes("errors building")),j=Z.message.includes("Configuration must export a valid object")||Z.message.includes("Configuration file is empty and exports nothing");if(E&&(j||B))throw Z;if(h&&(!E||!j))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(!E)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)j0.warn(`Slow configuration loading detected: ${Z.duration}ms for ${f.name}`);W.metrics=Z}return W}catch(W){let Z=Date.now()-w;throw j0.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:E="replace",verbose:B=!1}=$,h=Y||Ww.cwd(),j=[],F=await this.loadLocalConfiguration(J,U,h,f,W,E,B,Z,A);if(F)return j.push(...this.getLocalSearchPaths(J,U,h,f)),this.finalizeResult(F,j,Z,J,B);let T=await this.loadHomeConfiguration(J,U,W,E,B,Z);if(T)return j.push(...this.getHomeSearchPaths(J,U)),this.finalizeResult(T,j,Z,J,B);let H=await this.loadPackageJsonConfiguration(J,U,h,W,E,B,Z);if(H)return j.push(b$(h,"package.json")),this.finalizeResult(H,j,Z,J,B);if(j.push(...this.getAllSearchPaths(J,U,h,f)),w)throw e0.configNotFound(J,j,U);return{...await this.applyEnvironmentVariables(J,W,Z,B),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 E=W?k1($,U,f):U,B=this.getLocalDirectories(A,J);for(let h of B){if(f)j0.info(`Searching for configuration in: ${h}`);let j=this.fileLoader.generateConfigPaths($,h,w),F=await this.fileLoader.tryLoadFromPaths(j,E,{arrayStrategy:Y,verbose:f,cacheTtl:Z?.ttl,useCache:!Z?.ttl||Z.ttl>100});if(F){if(f)j0.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,J,U,Y){if(!$)return null;let f=Y?k1($,A,U):A,W=[b$(ow(),".config",$),b$(ow(),".config"),ow()];for(let Z of W){if(U)j0.info(`Checking home directory: ${Z}`);let E=this.fileLoader.generateConfigPaths($,Z,w),B=await this.fileLoader.tryLoadFromPaths(E,f,{arrayStrategy:J,verbose:U});if(B){if(U)j0.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration($,w,A,J,U,Y,f){let W=f?k1($,J,Y):J;try{let Z=b$(A,"package.json");if(!$f(Z))return null;let E=await import(Z),B=E[$],h=$;if(!B&&w)B=E[w],h=w;if(B&&typeof B==="object"&&!Array.isArray(B)){if(Y)j0.success(`Configuration loaded from package.json: ${h}`);return{config:Hf(W,B,U),source:{type:"package.json",path:Z,priority:30,timestamp:new Date}}}}catch(Z){if(Y)j0.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:k1($,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 e0.configValidation(J||"unknown",U,J)}checkCache($,w){let A=this.generateCacheKey($,w);return W1.get(A)||null}cacheResult($,w,A,J){let U=this.generateCacheKey($,J);W1.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$(ow(),".config",$),b$(ow(),".config"),ow()],J=[];for(let U of A)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}async loadConfigWithResult($){return this.loadConfig($)}}function rB($){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 c2($){return u0.loadConfig({...$,__strictErrorHandling:!0})}async function yh($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let J;if(A)J=await u0.loadConfig($);else J=await u0.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)j0.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 u0.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function u2($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await u0.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"&&rB(A)))return(await u0.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await u0.loadConfig({...$,cwd:$.cwd||Ww.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&rB(w)))return(await u0.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function v2($,w,A="replace"){let J=new UU;try{let U=await J.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function k1($,w,A=!1){let J=new JU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function Y(f,W=[]){let Z={...f};for(let[E,B]of Object.entries(f)){let h=[...W,E],j=[`${U}_${h.join("_").toUpperCase()}`,`${U}_${h.map((H)=>H.toUpperCase()).join("")}`,`${U}_${h.map((H)=>H.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let H of j)if(F=Ww.env[H],F!==void 0){T=H;break}if(F!==void 0&&T)if(typeof B==="boolean")Z[E]=["true","1","yes"].includes(F.toLowerCase());else if(typeof B==="number"){let H=Number(F);if(!Number.isNaN(H))Z[E]=H}else if(Array.isArray(B))try{Z[E]=JSON.parse(F)}catch{Z[E]=F.split(",").map((H)=>H.trim())}else Z[E]=F;else if(B&&typeof B==="object"&&!Array.isArray(B))Z[E]=Y(B,h)}return Z}return Y(w)}function n2($){let w=b$(Ww.cwd(),$.configDir),A=b$(Ww.cwd(),$.generatedDir),J=b$(A,"config-types.ts");if(!$f(kB(J)))lG(kB(J),{recursive:!0,mode:511});let U=$f(w)?tG(w).map((f)=>f.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],Y=`// Generated by bunfig v${G7}
|
|
158
158
|
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
159
|
-
`;
|
|
159
|
+
`;pG(J,Y,{mode:438})}function m2($){let w=null,A=null,J=()=>{if(!A)A=yh($).then((Y)=>{return w=Y,Y},(Y)=>{let f="defaultConfig"in $?$.defaultConfig:{};if(w=f,"verbose"in $&&$.verbose)j0.warn("Config loading failed, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);return f});return A},U="defaultConfig"in $?$.defaultConfig:{};return w=U,J(),new Proxy({},{get(Y,f){if(w)return w[f];let W=U[f];return J(),W},has(Y,f){return f in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(Y,f){return Object.getOwnPropertyDescriptor(w||U,f)},set(Y,f,W){if(!w)w={...U};return w[f]=W,!0}})}function d2($){let w=pB(q2.cwd(),$?.configDir||"./config");function A(){if(!T2(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),Y=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],f=G2(w).filter((Z)=>U.has(g8(Z))).map((Z)=>({base:Z.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Z})),W=new Map;for(let{base:Z,file:E}of f){let B=g8(E).toLowerCase(),h=W.get(Z);if(!h){W.set(Z,E);continue}let j=g8(h).toLowerCase();if(Y.indexOf(B)<Y.indexOf(j))W.set(Z,E)}return Array.from(W.entries()).map(([Z,E])=>({base:Z,file:E})).sort((Z,E)=>Z.base.localeCompare(E.base))}function J(){let U=A(),Y=U.map((E)=>E.base),f=Y.length?Y.map((E)=>`'${E}'`).join(" | "):"string",W=U.length?`{
|
|
160
160
|
${U.map((E)=>{let B=pB(w,E.file).replace(/\\/g,"/");return` '${E.base}': typeof import('${B}').default`}).join(`,
|
|
161
161
|
`)}
|
|
162
162
|
}`:"Record<string, any>";return`export type ConfigNames = ${f}
|
|
163
163
|
export type ConfigByName = ${W}
|
|
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 R7($,w={}){let A=wU.cwd();while(A.includes("storage"))A=fh(A,"..");let J=fh(A,$||"");if(w?.relative)return N7(wU.cwd(),J);return J}function H$(){if(c0.env.NODE_ENV==="test"||c0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _7(){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 xh{async format($){let w=await _7(),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 Ew{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={...AU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new xh,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{...e8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...e8};return{...e8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:AU.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 L7(this.config.logDirectory,Bh.F_OK|Bh.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await S7(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P0.from($);try{if(!iJ(this.currentLogFile))await o8(this.currentLogFile,"",{mode:420});if(U=Eh(this.currentLogFile,"a",420),y7(U,Z,{flag:"a"}),Wh(U),U!==void 0)s8(U),U=void 0;if((await Y1(this.currentLogFile)).size===0){if(await o8(this.currentLogFile,Z,{flag:"w",mode:420}),(await Y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{s8(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 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(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 a8(16).toString("hex")}generateKey(){return a8(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=a8(16),J=M7("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(),E=P0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=Fh(),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(H$())return;if(!this.shouldWriteToFile())return;let $=await Y1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await cJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await Y1(A).catch(()=>null))try{if(await hh(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await uJ(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 o8(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 Y1(A).catch(()=>null))await hh(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await cJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await uJ(f1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=Zh($),J=C7(w),U=Fh();await X7(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()})),iJ(this.currentLogFile))try{let $=Eh(this.currentLogFile,"r+");Wh($),s8($)}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 cJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await uJ(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()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H$())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=_.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${b.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(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(V7(w)||w.startsWith("./")||w.startsWith("../"))w=O7(w);else return null;return iJ(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":P7[$],j=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:b.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:b.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
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 K7($,w={}){let A=wU.cwd();while(A.includes("storage"))A=fh(A,"..");let J=fh(A,$||"");if(w?.relative)return R7(wU.cwd(),J);return J}function H$(){if(c0.env.NODE_ENV==="test"||c0.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function D7(){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 xh{async format($){let w=await D7(),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 Ew{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={...AU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new xh,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{...e8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...e8};return{...e8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:AU.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 S7(this.config.logDirectory,Bh.F_OK|Bh.W_OK)}catch(E){if(E instanceof Error&&"code"in E)if(E.code==="ENOENT")await V7(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 Z=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P0.from($);try{if(!iJ(this.currentLogFile))await o8(this.currentLogFile,"",{mode:420});if(U=Eh(this.currentLogFile,"a",420),L7(U,Z,{flag:"a"}),Wh(U),U!==void 0)s8(U),U=void 0;if((await Y1(this.currentLogFile)).size===0){if(await o8(this.currentLogFile,Z,{flag:"w",mode:420}),(await Y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(E){let B=E;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(Y<f-1){let h=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${Y+1}/${f}:`,h);let j=W*2**Y;await new Promise((F)=>setTimeout(F,j)),Y++;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(U!==void 0)try{s8(U)}catch(E){console.error("Debug: [writeToFile] Error closing file descriptor:",E)}}}catch(Z){if(Y===f-1){let B=Z,h=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),Z}Y++;let E=W*2**(Y-1);await new Promise((B)=>setTimeout(B,E))}})();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 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(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 a8(16).toString("hex")}generateKey(){return a8(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=a8(16),J=I7("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(),E=P0.allocUnsafe(16+W+16);return A.copy(E,0),Y.copy(E,16),f.copy(E,16+Y.length),Z.copy(E,16+W),{encrypted:E,iv:A}}async compressData($){return new Promise((w,A)=>{let J=Fh(),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(H$())return;if(!this.shouldWriteToFile())return;let $=await Y1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,J=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await cJ(this.config.logDirectory),Y=U.filter((Z)=>Z.startsWith(this.name)&&/\.log\.\d+$/.test(Z)).sort((Z,E)=>{let B=Number.parseInt(Z.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(E.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),f=Y.length>0?Number.parseInt(Y[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${f}`;if(await Y1(A).catch(()=>null))try{if(await hh(A,W),w.compress)try{let Z=`${W}.gz`;await this.compressLogFile(W,Z),await uJ(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 o8(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 Y1(A).catch(()=>null))await hh(A,Y)}if(this.currentLogFile=J,w.maxFiles){let Y=(await cJ(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,W)=>W.localeCompare(f));for(let f of Y.slice(w.maxFiles))await uJ(f1(this.config.logDirectory,f))}}}async compressLogFile($,w){let A=Zh($),J=y7(w),U=Fh();await _7(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()})),iJ(this.currentLogFile))try{let $=Eh(this.currentLogFile,"r+");Wh($),s8($)}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 cJ(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await uJ(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()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H$())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:J="",message:U,level:Y,showTimestamp:f=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(f)F.push(w);if(Y==="warning")F.push("WARN");else if(Y==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(J)F.push(J.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let Z=_.stdout.columns||120,E="";if(Y==="warning"||Y==="error")E=`${A} ${U}`;else if(Y==="info"||Y==="success")E=`${A} ${J} ${U}`;else E=`${A} ${J} ${b.cyan(U)}`;if(!f)return E.trim();let B=W(E).trim().length,h=W(w).length,j=Math.max(1,Z-2-B-h);return`${E.trim()}${" ".repeat(j)}${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;;",E="\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(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(O7(w)||w.startsWith("./")||w.startsWith("../"))w=X7(w);else return null;return iJ(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:E}=this.buildOutputTexts(f);if(this.shouldStyleConsole()){let h=this.options.showIcons===!1?"":b7[$],j=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:b.gray(Z),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:b.green(Z),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:h,tag:j,message:Z,level:$}),console.error(F),W){let T=W.split(`
|
|
167
167
|
`);for(let H of T)if(H.trim()&&!H.includes(f))console.error(this.formatConsoleMessage({timestamp:U,message:b.gray(` ${H}`),level:$,showTimestamp:!1}))}break}}else if(!H$()){if(console.error(`${Y} ${this.environment}.${$.toUpperCase()}: ${f}`),W)console.error(W)}let B=`${Y} ${this.environment}.${$.toUpperCase()}: ${E}
|
|
168
168
|
`;if(W)B+=`${W}
|
|
169
169
|
`;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress($,w=""){let A={update:(W,Z)=>{},finish:(W)=>{},interrupt:(W,Z)=>{}};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()&&!H$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Z)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Z!==void 0)this.activeProgressBar.message=Z;if(this.shouldStyleConsole()&&!H$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Z="info")=>{if(!H$()&&_.stdout.isTTY)_.stdout.write(`
|
|
170
170
|
`);if(this[Z==="warning"?"warn":Z](W),this.activeProgressBar&&this.shouldStyleConsole()&&!H$()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",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(),U=Math.round(J-w),Y=`${$} completed in ${U}ms`,f=new Date,W=this.formatConsoleTimestamp(f),E=`${this.formatFileTimestamp(f)} ${this.environment}.INFO: ${Y}`;if(A)E+=` ${JSON.stringify(A)}`;if(E+=`
|
|
171
|
-
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!H$())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 Ew(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(H$())throw Error("createReadStream is not supported in browser environments");if(!iJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zh(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=P0.isBuffer($)?$:P0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=
|
|
171
|
+
`,E=E.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:B,message:`${Y}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!H$())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 Ew(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(H$())throw Error("createReadStream is not supported in browser environments");if(!iJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zh(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=P0.isBuffer($)?$:P0.from($,"base64"),U=J.subarray(0,16),Y=J.subarray(J.length-16),f=J.subarray(16,J.length-16),W=C7("aes-256-gcm",A,U);W.setAuthTag(Y);let Z=W.update(f),E=W.final(),B=Z.length+E.length,h=P0.allocUnsafe(B);return Z.copy(h,0),E.copy(h,Z.length),h.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 H$()}isServerMode(){return!H$()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),J=this.formatFileTimestamp(w),{consoleText:U,fileText:Y}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
172
172
|
`),Z=Math.max(...W.map((j)=>j.length))+2,E=`┌${"─".repeat(Z)}┐`,B=`└${"─".repeat(Z)}┘`,h=W.map((j)=>{return this.formatConsoleMessage({timestamp:A,message:b.cyan(j),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(E),showTimestamp:!1})),h.forEach((j)=>console.error(j)),console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(B),showTimestamp:!1}))}else if(!H$())console.error(`${J} ${this.environment}.INFO: [BOX] ${Y}`);let f=`${J} ${this.environment}.INFO: [BOX] ${Y}
|
|
173
173
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}async prompt($){if(H$())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let A=(J)=>{let U=J.toString().trim().toLowerCase();_.stdin.removeListener("data",A);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),w(U==="y"||U==="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 Z=/%([sdijfo%])/g,E=0;if(A=$.replace(Z,(B,h)=>{if(h==="%")return"%";if(E>=w.length)return B;let j=w[E++];switch(h){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 B}}),E<w.length)A+=` ${w.slice(E).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:J,fileText:U}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let Z=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",E=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${E}${Z} ${b.cyan(J)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
174
174
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),J=Math.round($.barLength*A/100),U=$.barLength-J,Y=b.green("━".repeat(J)),f=b.gray("━".repeat(U)),W=`[${Y}${f}]`,Z=`${A}%`.padStart(4),E=$.message?` ${$.message}`:"",B=this.options.showIcons===!1?"":w||A===100?b.green("✓"):b.blue("▶"),h=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",j=`\r${B}${h} ${W} ${Z}${E}`,F=_.stdout.columns||80,T=" ".repeat(Math.max(0,F-j.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${j}${T}`,_.stdout.write($.lastRenderedLine),w)_.stdout.write(`
|
|
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 cJ(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=f1(this.config.logDirectory,J);if($.before)try{if((await Y1(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 uJ(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 uG,vG=($)=>$,mG=($,w)=>{for(var A in w)uG($,A,{get:w[A],enumerable:!0,configurable:!0,set:nG.bind(w,A)})},dG=($,w)=>()=>($&&(w=$($=0)),w),Hh,Lh,W1,b1,Sh,d2,g2,aB,nJ,Jf,S$,l,l2,sB,t2,oB,p2,r2,l8,a2,eB,$h,t8,s2,o2,e2,$7,mJ,Vh,w7,V$,A7,J7,wh,dJ,Uf,z$,Q,U7,Ah,Y7,Jh,f7,Z7,p8,W7,Uh,Yh,E7,r8,B7,h7,F7,j7,z7,gJ,Oh,H7,T7="0.15.6",l$,eJ,x1,Yf,ff,$U,Zf,Wf,P1,Ef,Bf,e0,Xh,_h,j0,u0,Dh,kh,G7,K7,Qh,AU,fI,N$,b,GI,D7,qI,k7,NI,RI,jh,KI,Q7,x7,MI,zh,II,CI,yI,LI,SI,e8,P7,VI;var qf=X$(()=>{uG=Object.defineProperty;Hh={};mG(Hh,{withErrorRecovery:()=>Rh,tryLoadConfig:()=>u2,loadConfigWithResult:()=>i2,loadConfig:()=>yh,isRetryableError:()=>D2,isConfigNotFoundError:()=>_2,isBunfigError:()=>Kh,globalPerformanceMonitor:()=>b1,globalCache:()=>W1,getEnvOrDefault:()=>k2,generateConfigTypes:()=>v2,defaultGeneratedDir:()=>kh,defaultConfigDir:()=>Dh,deepMergeWithArrayStrategy:()=>Hf,deepMerge:()=>Mh,createLibraryConfig:()=>n2,config:()=>c2,bunfigPlugin:()=>m2,applyEnvVarsToConfig:()=>k1,TypeGenerationError:()=>Wf,SchemaValidationError:()=>P1,PluginError:()=>Bf,PerformanceMonitor:()=>Ff,FileSystemError:()=>Zf,ErrorFactory:()=>e0,EnvVarError:()=>$U,EnvProcessor:()=>JU,ConfigValidator:()=>Tf,ConfigValidationError:()=>Yf,ConfigNotFoundError:()=>eJ,ConfigMergeError:()=>ff,ConfigLoader:()=>Gf,ConfigLoadError:()=>x1,ConfigFileLoader:()=>UU,ConfigCache:()=>hf,CacheUtils:()=>Sh,BunfigError:()=>l$,BrowserConfigError:()=>Ef,ArrayMergeStrategies:()=>Xh});G7=dG(async()=>{Lh=import.meta.require,W1=new hf,b1=new Ff,Sh={createKey:q2,isEquivalent:N2,estimateMemoryUsage:R2},d2=pJ(wf.cwd(),"config"),g2=pJ(wf.cwd(),"src/generated"),aB=tJ.env.CLARITY_LOG_DIR||aG(I2(),"logs"),nJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Jf=await C2(),S$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},l=S$,l2=S$.red,sB=S$.green,t2=S$.yellow,oB=S$.blue,p2=S$.magenta,r2=S$.cyan,l8=S$.white,a2=S$.gray,eB=S$.bgRed,$h=S$.bgYellow,t8=S$.bold,s2=S$.dim,o2=S$.italic,e2=S$.underline,$7=S$.reset,mJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vh={debug:"\uD83D\uDD0D",info:oB("ℹ"),success:sB("✓"),warning:$h(l8(t8(" WARN "))),error:eB(l8(t8(" ERROR ")))},w7=new aJ("stacks"),V$=new aJ("bunfig",{showTags:!0}),A7=P$(Q1.cwd(),"config"),J7=P$(Q1.cwd(),"src/generated"),wh=lJ.env.CLARITY_LOG_DIR||pG(V2(),"logs"),dJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Uf=await O2(),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$,U7=z$.red,Ah=z$.green,Y7=z$.yellow,Jh=z$.blue,f7=z$.magenta,Z7=z$.cyan,p8=z$.white,W7=z$.gray,Uh=z$.bgRed,Yh=z$.bgYellow,E7=z$.bgGray,r8=z$.bold,B7=z$.dim,h7=z$.italic,F7=z$.underline,j7=z$.strikethrough,z7=z$.reset,gJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Oh={debug:"\uD83D\uDD0D",info:Jh("ℹ"),success:Ah("✓"),warning:Yh(p8(r8(" WARN "))),error:Uh(p8(r8(" ERROR ")))},H7=new oJ("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}`}},eJ=class extends l${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})}},x1=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}},Yf=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})}},ff=class extends l${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}},$U=class extends l${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})}},Zf=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}},Wf=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}},P1=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})}},Ef=class extends l${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})}},Bf=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}},e0={configNotFound($,w,A){return new eJ($,w,A)},configLoad($,w,A){return new x1($,w,A)},configValidation($,w,A){return new Yf($,w,A)},configMerge($,w,A,J){return new ff($,w,A,J)},envVar($,w,A,J){return new $U($,w,A,J)},fileSystem($,w,A){return new Zf($,w,A)},typeGeneration($,w,A){return new Wf($,w,A)},schemaValidation($,w,A){return new P1($,w,A)},browserConfig($,w,A,J){return new Ef($,w,A,J)},plugin($,w,A){return new Bf($,w,A)}},Xh={replace:"replace",concat:"concat",smart:"smart"},_h=/^https?:\/\//,j0=new oJ("bunfig",{showTags:!0}),u0=new Gf,Dh=b$(Ww.cwd(),"config"),kh=b$(Ww.cwd(),"src/generated")});K7=wU.env.CLARITY_LOG_DIR||q7(R7(),"logs"),Qh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:K7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},AU={...Qh},fI=(async()=>{try{let{loadConfig:$}=await G7().then(()=>Hh),w=await $({name:"clarity",alias:"logging",defaultConfig:Qh,cwd:wU.cwd()});if(w)Object.assign(AU,w)}catch{}return AU})();N$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=N$,GI=N$.red,D7=N$.green,qI=N$.yellow,k7=N$.blue,NI=N$.magenta,RI=N$.cyan,jh=N$.white,KI=N$.gray,Q7=N$.bgRed,x7=N$.bgYellow,MI=N$.bgGray,zh=N$.bold,II=N$.dim,CI=N$.italic,yI=N$.underline,LI=N$.strikethrough,SI=N$.reset,e8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},P7={debug:"\uD83D\uDD0D",info:k7("ℹ"),success:D7("✓"),warning:x7(jh(zh(" WARN "))),error:Q7(jh(zh(" ERROR ")))};VI=new Ew("stacks")});var E1={};JZ(E1,{safeStringify:()=>J0,safeDeleteFile:()=>Kf,resolvePathRewrite:()=>Rf,redactSensitive:()=>YU,isValidRootCA:()=>Nf,isSingleProxyOptions:()=>c1,isSingleProxyConfig:()=>n7,isMultiProxyOptions:()=>hw,isMultiProxyConfig:()=>ch,getSudoPassword:()=>Bw,getPrimaryDomain:()=>fU,extractHostname:()=>v7,execSudoSync:()=>i1,debugLog:()=>z});import{execSync as Ph}from"node:child_process";import*as ih from"node:fs/promises";function Bw(){return process.env.SUDO_PASSWORD}function i1($){let w=Bw(),A=$.replace(/'/g,"'\\''");if(w)return Ph(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return Ph(`sudo sh -c '${A}'`,{encoding:"utf-8"})}function z($,w,A){if(A)b7.debug(`[rpx:${$}] ${w}`)}function u7($){let w=$.toLowerCase();return i7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function YU($){if(Array.isArray($))return $.map((A)=>YU(A));if(typeof $==="string")return c7.test($)?bh:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(u7(A)){w[A]=bh;continue}w[A]=YU(J)}return w}function J0($,w){return JSON.stringify(YU($),null,w)}function v7($){if(hw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(c1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function Nf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function fU($){if(!$)return"stacks.localhost";if(hw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(c1($))return $.to||"stacks.localhost";return"stacks.localhost"}function ch($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function hw($){return"proxies"in $&&Array.isArray($.proxies)}function c1($){return"to"in $&&typeof $.to==="string"}function n7($){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 Kf($,w){try{await ih.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var b7,bh="[redacted]",i7,c7;var U$=X$(()=>{qf();b7=new Ew("rpx",{showTags:!1});i7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),c7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as ZU}from"node:child_process";import{homedir as m7}from"node:os";import{join as d7}from"node:path";function WU(){return d7(m7(),"Library/Keychains/login.keychain-db")}function If(){return[h1,WU()]}function uh($,w=Mf){let A=ZU(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),J=[];for(let U of A.split(`
|
|
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 cJ(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=f1(this.config.logDirectory,J);if($.before)try{if((await Y1(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 uJ(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 vG,nG=($)=>$,dG=($,w)=>{for(var A in w)vG($,A,{get:w[A],enumerable:!0,configurable:!0,set:mG.bind(w,A)})},gG=($,w)=>()=>($&&(w=$($=0)),w),Hh,Lh,W1,b1,Sh,g2,l2,aB,nJ,Jf,S$,l,t2,sB,p2,oB,r2,a2,l8,s2,eB,$h,t8,o2,e2,$7,w7,mJ,Vh,A7,V$,J7,U7,wh,dJ,Uf,z$,Q,Y7,Ah,f7,Jh,Z7,W7,p8,E7,Uh,Yh,B7,r8,h7,F7,j7,z7,H7,gJ,Oh,T7,G7="0.15.6",t$,eJ,x1,Yf,ff,$U,Zf,Wf,P1,Ef,Bf,e0,Xh,_h,j0,u0,Dh,kh,q7,M7,Qh,AU,BI,N$,b,KI,k7,MI,Q7,II,CI,jh,yI,x7,P7,LI,zh,SI,VI,OI,XI,_I,e8,b7,DI;var qf=X$(()=>{vG=Object.defineProperty;Hh={};dG(Hh,{withErrorRecovery:()=>Rh,tryLoadConfig:()=>v2,loadConfigWithResult:()=>c2,loadConfig:()=>yh,isRetryableError:()=>k2,isConfigNotFoundError:()=>D2,isBunfigError:()=>Kh,globalPerformanceMonitor:()=>b1,globalCache:()=>W1,getEnvOrDefault:()=>Q2,generateConfigTypes:()=>n2,defaultGeneratedDir:()=>kh,defaultConfigDir:()=>Dh,deepMergeWithArrayStrategy:()=>Hf,deepMerge:()=>Mh,createLibraryConfig:()=>m2,config:()=>u2,bunfigPlugin:()=>d2,applyEnvVarsToConfig:()=>k1,TypeGenerationError:()=>Wf,SchemaValidationError:()=>P1,PluginError:()=>Bf,PerformanceMonitor:()=>Ff,FileSystemError:()=>Zf,ErrorFactory:()=>e0,EnvVarError:()=>$U,EnvProcessor:()=>JU,ConfigValidator:()=>Tf,ConfigValidationError:()=>Yf,ConfigNotFoundError:()=>eJ,ConfigMergeError:()=>ff,ConfigLoader:()=>Gf,ConfigLoadError:()=>x1,ConfigFileLoader:()=>UU,ConfigCache:()=>hf,CacheUtils:()=>Sh,BunfigError:()=>t$,BrowserConfigError:()=>Ef,ArrayMergeStrategies:()=>Xh});q7=gG(async()=>{Lh=import.meta.require,W1=new hf,b1=new Ff,Sh={createKey:N2,isEquivalent:R2,estimateMemoryUsage:K2},g2=pJ(wf.cwd(),"config"),l2=pJ(wf.cwd(),"src/generated"),aB=tJ.env.CLARITY_LOG_DIR||sG(C2(),"logs"),nJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:aB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Jf=await y2(),S$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},l=S$,t2=S$.red,sB=S$.green,p2=S$.yellow,oB=S$.blue,r2=S$.magenta,a2=S$.cyan,l8=S$.white,s2=S$.gray,eB=S$.bgRed,$h=S$.bgYellow,t8=S$.bold,o2=S$.dim,e2=S$.italic,$7=S$.underline,w7=S$.reset,mJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Vh={debug:"\uD83D\uDD0D",info:oB("ℹ"),success:sB("✓"),warning:$h(l8(t8(" WARN "))),error:eB(l8(t8(" ERROR ")))},A7=new aJ("stacks"),V$=new aJ("bunfig",{showTags:!0}),J7=P$(Q1.cwd(),"config"),U7=P$(Q1.cwd(),"src/generated"),wh=lJ.env.CLARITY_LOG_DIR||rG(O2(),"logs"),dJ={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Uf=await X2(),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$,Y7=z$.red,Ah=z$.green,f7=z$.yellow,Jh=z$.blue,Z7=z$.magenta,W7=z$.cyan,p8=z$.white,E7=z$.gray,Uh=z$.bgRed,Yh=z$.bgYellow,B7=z$.bgGray,r8=z$.bold,h7=z$.dim,F7=z$.italic,j7=z$.underline,z7=z$.strikethrough,H7=z$.reset,gJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Oh={debug:"\uD83D\uDD0D",info:Jh("ℹ"),success:Ah("✓"),warning:Yh(p8(r8(" WARN "))),error:Uh(p8(r8(" ERROR ")))},T7=new oJ("stacks"),t$=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}`}},eJ=class extends t${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})}},x1=class extends t${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}},Yf=class extends t${code="CONFIG_VALIDATION_ERROR";constructor(w,A,J){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:J,validationErrors:A,errorCount:A.length})}},ff=class extends t${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}},$U=class extends t${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})}},Zf=class extends t${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}},Wf=class extends t${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}},P1=class extends t${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 t${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})}},Bf=class extends t${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}},e0={configNotFound($,w,A){return new eJ($,w,A)},configLoad($,w,A){return new x1($,w,A)},configValidation($,w,A){return new Yf($,w,A)},configMerge($,w,A,J){return new ff($,w,A,J)},envVar($,w,A,J){return new $U($,w,A,J)},fileSystem($,w,A){return new Zf($,w,A)},typeGeneration($,w,A){return new Wf($,w,A)},schemaValidation($,w,A){return new P1($,w,A)},browserConfig($,w,A,J){return new Ef($,w,A,J)},plugin($,w,A){return new Bf($,w,A)}},Xh={replace:"replace",concat:"concat",smart:"smart"},_h=/^https?:\/\//,j0=new oJ("bunfig",{showTags:!0}),u0=new Gf,Dh=b$(Ww.cwd(),"config"),kh=b$(Ww.cwd(),"src/generated")});M7=wU.env.CLARITY_LOG_DIR||N7(K7(),"logs"),Qh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:M7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},AU={...Qh},BI=(async()=>{try{let{loadConfig:$}=await q7().then(()=>Hh),w=await $({name:"clarity",alias:"logging",defaultConfig:Qh,cwd:wU.cwd()});if(w)Object.assign(AU,w)}catch{}return AU})();N$={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=N$,KI=N$.red,k7=N$.green,MI=N$.yellow,Q7=N$.blue,II=N$.magenta,CI=N$.cyan,jh=N$.white,yI=N$.gray,x7=N$.bgRed,P7=N$.bgYellow,LI=N$.bgGray,zh=N$.bold,SI=N$.dim,VI=N$.italic,OI=N$.underline,XI=N$.strikethrough,_I=N$.reset,e8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},b7={debug:"\uD83D\uDD0D",info:Q7("ℹ"),success:k7("✓"),warning:P7(jh(zh(" WARN "))),error:x7(jh(zh(" ERROR ")))};DI=new Ew("stacks")});var E1={};JZ(E1,{safeStringify:()=>J0,safeDeleteFile:()=>Kf,resolvePathRewrite:()=>Rf,redactSensitive:()=>YU,isValidRootCA:()=>Nf,isSingleProxyOptions:()=>c1,isSingleProxyConfig:()=>m7,isMultiProxyOptions:()=>hw,isMultiProxyConfig:()=>ch,getSudoPassword:()=>Bw,getPrimaryDomain:()=>fU,extractHostname:()=>n7,execSudoSync:()=>i1,debugLog:()=>z});import{execSync as Ph}from"node:child_process";import*as ih from"node:fs/promises";function Bw(){return process.env.SUDO_PASSWORD}function i1($){let w=Bw(),A=$.replace(/'/g,"'\\''");if(w)return Ph(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Ph(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function z($,w,A){if(A)i7.debug(`[rpx:${$}] ${w}`)}function v7($){let w=$.toLowerCase();return c7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function YU($){if(Array.isArray($))return $.map((A)=>YU(A));if(typeof $==="string")return u7.test($)?bh:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,J]of Object.entries($)){if(v7(A)){w[A]=bh;continue}w[A]=YU(J)}return w}function J0($,w){return JSON.stringify(YU($),null,w)}function n7($){if(hw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(c1($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function Nf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function fU($){if(!$)return"stacks.localhost";if(hw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(c1($))return $.to||"stacks.localhost";return"stacks.localhost"}function ch($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function hw($){return"proxies"in $&&Array.isArray($.proxies)}function c1($){return"to"in $&&typeof $.to==="string"}function m7($){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 Kf($,w){try{await ih.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var i7,bh="[redacted]",c7,u7;var U$=X$(()=>{qf();i7=new Ew("rpx",{showTags:!1});c7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),u7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as ZU}from"node:child_process";import{homedir as d7}from"node:os";import{join as g7}from"node:path";function WU(){return g7(d7(),"Library/Keychains/login.keychain-db")}function If(){return[h1,WU()]}function uh($,w=Mf){let A=ZU(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),J=[];for(let U of A.split(`
|
|
176
176
|
`)){let Y=U.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(Y)J.push(Y[1].toUpperCase())}return J}function Cf($){if(process.platform!=="darwin")return;let w=OJ($.caPath);if(!w)return;let A=$.commonName??Mf,J=$.keychains??If();for(let U of J)for(let Y of uh(U,A)){if(Y===w)continue;try{if(U.startsWith("/Library"))i1(`security delete-certificate -Z ${Y} "${U}"`);else ZU(`security delete-certificate -Z ${Y} "${U}"`,{stdio:"ignore"});z("ssl",`Removed stale Root CA ${Y} from ${U}`,$.verbose)}catch{}}}function yf($,w,A){if(process.platform!=="darwin")return EU($,A);try{let U=ZU(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return z("ssl",`verify-cert ${w}: ${U?"trusted":"not trusted"}`,A?.verbose),U}catch{return!1}}function EU($,w){let A=OJ($);if(!A)return!1;for(let J of If())try{let U=ZU(`security find-certificate -a -Z "${J}" 2>/dev/null || true`,{encoding:"utf8"});for(let Y of U.split(`
|
|
177
|
-
`))if(Y.toUpperCase().includes("SHA-256")){if(Y.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return z("ssl",`Root CA fingerprint found in ${J}`,w?.verbose),!0}}catch{}return!1}var B1="-d -r trustRoot -p ssl -p basic",h1="/Library/Keychains/System.keychain",Mf="rpx.localhost";var Lf=X$(()=>{x8();U$()});import{execSync as F1}from"node:child_process";import T$ from"node:fs/promises";import*as Sf from"node:os";import{homedir as BU}from"node:os";import{join as O$}from"node:path";import*as $w from"node:process";function mh($){return{caCertPath:O$($,
|
|
177
|
+
`))if(Y.toUpperCase().includes("SHA-256")){if(Y.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===A)return z("ssl",`Root CA fingerprint found in ${J}`,w?.verbose),!0}}catch{}return!1}var B1="-d -r trustRoot -p ssl -p basic",h1="/Library/Keychains/System.keychain",Mf="rpx.localhost";var Lf=X$(()=>{x8();U$()});import{execSync as F1}from"node:child_process";import T$ from"node:fs/promises";import*as Sf from"node:os";import{homedir as BU}from"node:os";import{join as O$}from"node:path";import*as $w from"node:process";function mh($){return{caCertPath:O$($,t7),caKeyPath:O$($,p7)}}async function r7($,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 z("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:J}}catch(A){return z("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function vh($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function dh($){let A=fU($).replace(/\*/g,"wildcard"),J=O$(BU(),".stacks","ssl"),U=J;if(typeof $?.https==="object")return U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:J,{caCertPath:$.https.caCertPath||O$(U,`${A}.ca.crt`),certPath:$.https.certPath||O$(U,`${A}.crt`),keyPath:$.https.keyPath||O$(U,`${A}.key`)};return{caCertPath:O$(U,`${A}.ca.crt`),certPath:O$(U,`${A}.crt`),keyPath:O$(U,`${A}.key`)}}function nh($){let w=new Set;if(hw($))$.proxies.forEach((A)=>{let J=A.to||"rpx.localhost";vh(J).forEach((U)=>w.add(U))});else if(c1($)){let A=$.to||"rpx.localhost";vh(A).forEach((J)=>w.add(J))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function j1($){if(ww&&!$.forceRegenerate){z("ssl","Using cached SSL configuration",$.verbose);return}a7();let w=hw($)?$.proxies.map((B)=>B.to):[$.to];z("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=u1($,$.verbose),J=A.basePath||O$(BU(),".stacks","ssl");await T$.mkdir(J,{recursive:!0});let U=mh(J),Y=await r7(U,$.verbose),f=!1;if(!Y){if($.verbose)R.info("Generating Root CA certificate (one-time)...");Y=await V8(A);try{await Promise.all([T$.writeFile(U.caCertPath,Y.certificate),T$.writeFile(U.caKeyPath,Y.privateKey,{mode:384})]),f=!0,z("ssl",`Persisted Root CA at ${U.caCertPath}`,$.verbose)}catch(B){throw z("ssl",`Error saving Root CA files: ${B}`,$.verbose),Error(`Failed to save Root CA files: ${B}`)}}else z("ssl",`Reusing existing Root CA from ${U.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let W=await O8({...A,rootCA:{certificate:Y.certificate,privateKey:Y.privateKey}});try{await Promise.all([T$.writeFile(A.certPath,W.certificate),T$.writeFile(A.keyPath,W.privateKey),T$.writeFile(A.caCertPath,Y.certificate)]),z("ssl","Certificate files saved successfully",$.verbose)}catch(B){throw z("ssl",`Error saving certificate files: ${B}`,$.verbose),Error(`Failed to save certificate files: ${B}`)}if(f?!1:await lh(U.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(z("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(ww={key:W.privateKey,cert:W.certificate,ca:Y.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($w.platform==="darwin")try{Cf({caPath:U.caCertPath,verbose:$.verbose});let B=WU();try{F1(`security add-trusted-cert ${B1} -k "${B}" "${U.caCertPath}"`,{stdio:"ignore"})}catch{}if(i1(`security add-trusted-cert ${B1} -k ${h1} "${U.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");E=!0;let h=O$(J,"trust-rpx-cert.sh"),j=`#!/bin/bash
|
|
178
178
|
echo "Trusting RPX Root CA"
|
|
179
179
|
sudo security add-trusted-cert ${B1} -k ${h1} "${U.caCertPath}"
|
|
180
180
|
echo "Root CA trusted! Please restart your browser."
|
|
@@ -196,14 +196,14 @@ $store.Open("ReadWrite")
|
|
|
196
196
|
$store.Add($cert)
|
|
197
197
|
$store.Close()
|
|
198
198
|
Write-Host "Root CA trusted successfully!"
|
|
199
|
-
`,h=O$(Sf.tmpdir(),"rpx-trust.ps1");if(await T$.writeFile(h,B),F1(`powershell -ExecutionPolicy Bypass -File "${h}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");E=!0}catch(B){if($.verbose)R.warn(`Could not trust certificate: ${B}`)}else try{await X8(W,Y.certificate,A),E=!0}catch(B){if($.verbose)R.warn(`Could not add certificate to trust store: ${B}`)}if(ww={key:W.privateKey,cert:W.certificate,ca:Y.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 r7(){ww=null}async function v0($){if(!$)return null;if(ww)return ww;let w=u1($);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 z("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;z("ssl",`Trust check: hasFlag=${Y}, flagValue=${f}, shouldCheckTrust=${W}`,$.verbose);let Z=w.basePath||O$(BU(),".stacks","ssl"),E=mh(Z);if(!(W?await lh(E.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[h,j,F]=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(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(hw($))try{let{X509Certificate:T}=await import("node:crypto"),G=new T(j).subjectAltName||"",N=$.proxies.map((K)=>K.to).filter((K)=>!G.includes(`DNS:${K}`));if(N.length>0)return z("ssl",`Certificate missing SANs for: ${N.join(", ")}, will regenerate`,$.verbose),null}catch(T){z("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),ww={key:h,cert:j,ca:F},ww}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function u1($,w){let A=fU($);z("ssl",`Primary domain: ${A}`,w);let J=dh($),U=O$(BU(),".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(nh($)).map((W)=>({type:2,value:W}))};if(Nf($.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(nh($)).map((Y)=>({type:2,value:Y}))}}async function gh($,w){let A=dh({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((U)=>Kf(U,w)))}async function lh($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),$w.platform==="darwin"){if(w?.serverName)return yf($,w.serverName,{verbose:w.verbose});return EU($,{verbose:w.verbose})}else if($w.platform==="win32")try{let J=F1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return z("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(F1(U).toString().includes(J))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if($w.platform==="linux")try{let J=F1(`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(F1(`find ${Y} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return z("ssl",`Certificate fingerprint found in ${Y}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${$w.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var ww=null,l7="rpx-root-ca.crt",t7="rpx-root-ca.key";var hU=X$(()=>{OB();p0();Q8();Lf();U$();Lf();x8()});function v1($,w){return async(A)=>{let J=new URL(A.url),Y=(A.headers.get("host")||"").split(":")[0],f=$(Y);if(!f)return z("request",`No route found for host: ${Y}`,w),new Response(`No proxy configured for ${Y}`,{status:404});let W=f.sourceHost,Z=J.pathname,E=Rf(J.pathname,f.pathRewrites);if(E)W=E.targetHost,Z=E.targetPath,z("request",`Path rewrite: ${J.pathname} → ${W}${Z}`,w);let B=`http://${W}${Z}${J.search}`;try{let h=new Headers(A.headers);if(h.set("host",W),f.changeOrigin)h.set("origin",`http://${f.sourceHost}`);h.set("x-forwarded-for","127.0.0.1"),h.set("x-forwarded-proto","https"),h.set("x-forwarded-host",Y);let j=await fetch(B,{method:A.method,headers:h,body:A.body,redirect:"manual"});if(f.cleanUrls&&J.pathname.endsWith(".html")){let T=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:T}})}let F=new Headers(j.headers);return new Response(j.body,{status:j.status,statusText:j.statusText,headers:F})}catch(h){return z("request",`Proxy error for ${Y}: ${h}`,w),new Response(`Proxy Error: ${h}`,{status:502})}}}var FU=X$(()=>{U$();U$()});import*as jU from"node:fs";import*as i$ from"node:fs/promises";import{homedir as a7}from"node:os";import*as Vf from"node:path";import*as zU from"node:process";function Aw(){return Vf.join(a7(),".stacks","rpx","registry.d")}function n1($){return typeof $==="string"&&$.length>0&&$.length<=128&&s7.test($)}function Of($,w){if(!n1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return Vf.join($,`${w}.json`)}function t$($){if(!Number.isInteger($)||$<=0)return!1;try{return zU.kill($,0),!0}catch(w){return w.code==="EPERM"}}function th($){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"&&n1(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 o7($){await i$.mkdir($,{recursive:!0})}async function ph($,w=Aw(),A){if(!th($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await o7(w);let J=Of(w,$.id),U=`${J}.tmp.${zU.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await i$.writeFile(U,Y,{encoding:"utf8",mode:420}),await i$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await i$.unlink(U).catch(()=>{}),f}}async function Xf($,w=Aw(),A){let J=Of(w,$);try{await i$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function e7($,w=Aw(),A){let J=Of(w,$);try{let U=await i$.readFile(J,"utf8"),Y=JSON.parse(U);if(!th(Y))return z("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 z("registry",`entry ${$} has invalid JSON, removing`,A),await i$.unlink(J).catch(()=>{}),null;throw U}}async function Fw($=Aw(),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(!n1(Y))continue;let f=await e7(Y,$,w);if(f)J.push(f)}return J}async function HU($=Aw(),w){let A=await Fw($,w),J=0;for(let U of A){if(U.pid===void 0)continue;if(!t$(U.pid))z("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await Xf(U.id,$,w).catch(()=>{}),J++}return J}function _f($,w={}){let A=w.dir??Aw(),J=w.debounceMs??100,U=w.pollMs??Math.max(J*2,250),Y=w.verbose;jU.mkdirSync(A,{recursive:!0});let f=null,W=!1,Z=null,E=!1,B=(G)=>{return JSON.stringify(G.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)))},h=()=>{if(f=null,W)return;Fw(A,Y).then((G)=>{return Z=B(G),$(G)}).catch((G)=>{z("registry",`watcher onChange failed: ${G}`,Y)})},j=()=>{if(W)return;if(f)clearTimeout(f);f=setTimeout(h,J)},T=setInterval(()=>{if(W||E)return;E=!0,Fw(A,Y).then((G)=>{if(B(G)!==Z)j()}).catch((G)=>{z("registry",`watcher poll failed: ${G}`,Y)}).finally(()=>{E=!1})},U),H=jU.watch(A,{persistent:!0},(G,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;j()});return H.on("error",(G)=>{z("registry",`watcher error: ${G}`,Y)}),j(),{close:()=>{if(W=!0,f)clearTimeout(f);clearInterval(T),H.close()}}}var s7;var m1=X$(()=>{U$();s7=/^[a-zA-Z0-9._-]+$/});import{spawn as $q}from"node:child_process";import*as jw from"node:fs/promises";import{homedir as wq}from"node:os";import*as d1 from"node:path";import*as p$ from"node:process";function n0(){return d1.join(wq(),".stacks","rpx")}function ah($=n0()){return d1.join($,"daemon.pid")}async function rh($=n0()){try{let w=await jw.readFile(ah($),"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 Aq($=n0()){await jw.unlink(ah($)).catch(()=>{})}function Jq(){let $=p$.execPath,w=d1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&p$.argv[1])return[$,p$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function sh($={}){let w=$.rpxDir??n0(),A=$.verbose??!1;await Jw({rpxDir:w,verbose:A}).catch((B)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${B}`,A)});let J=await rh(w);if(J!==null&&t$(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await Aq(w);await jw.mkdir(w,{recursive:!0});let U=$.spawnCommand??Jq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=$q(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??p$.cwd(),env:$.spawnEnv?{...p$.env,...$.spawnEnv}:p$.env});Y.unref();let f=null;Y.once("error",(B)=>{f=B});let W=$.startupTimeoutMs??5000,Z=$.pollIntervalMs??50,E=Date.now()+W;while(Date.now()<E){if(f)throw f;let B=await rh(w);if(B!==null&&t$(B))return z("daemon",`daemon registered with pid=${B}`,A),{pid:B,spawned:!0};await new Promise((h)=>setTimeout(h,Z))}if(f)throw f;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var Df=X$(()=>{p0();hU();FU();m1();z1();U$()});import*as Uw from"node:fs/promises";import{homedir as Uq}from"node:os";import*as kf from"node:path";function eh(){return kf.join(Uq(),".stacks","rpx")}function Qf($=eh()){return kf.join($,Yq)}async function GU($=eh()){try{let w=await Uw.readFile(Qf($),"utf8"),A=JSON.parse(w);if(A.version!==TU||!Array.isArray(A.resolvers))return null;return{version:TU,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 $F($,w){await Uw.mkdir($,{recursive:!0}),await Uw.writeFile(Qf($),`${JSON.stringify(w,null,2)}
|
|
200
|
-
`,"utf8")}async function xf($){await Uw.rm(Qf($),{force:!0})}function wF($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;return w}function
|
|
199
|
+
`,h=O$(Sf.tmpdir(),"rpx-trust.ps1");if(await T$.writeFile(h,B),F1(`powershell -ExecutionPolicy Bypass -File "${h}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");E=!0}catch(B){if($.verbose)R.warn(`Could not trust certificate: ${B}`)}else try{await X8(W,Y.certificate,A),E=!0}catch(B){if($.verbose)R.warn(`Could not add certificate to trust store: ${B}`)}if(ww={key:W.privateKey,cert:W.certificate,ca:Y.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 a7(){ww=null}async function v0($){if(!$)return null;if(ww)return ww;let w=u1($);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 z("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;z("ssl",`Trust check: hasFlag=${Y}, flagValue=${f}, shouldCheckTrust=${W}`,$.verbose);let Z=w.basePath||O$(BU(),".stacks","ssl"),E=mh(Z);if(!(W?await lh(E.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[h,j,F]=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(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(hw($))try{let{X509Certificate:T}=await import("node:crypto"),G=new T(j).subjectAltName||"",N=$.proxies.map((K)=>K.to).filter((K)=>!G.includes(`DNS:${K}`));if(N.length>0)return z("ssl",`Certificate missing SANs for: ${N.join(", ")}, will regenerate`,$.verbose),null}catch(T){z("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),ww={key:h,cert:j,ca:F},ww}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function u1($,w){let A=fU($);z("ssl",`Primary domain: ${A}`,w);let J=dh($),U=O$(BU(),".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(nh($)).map((W)=>({type:2,value:W}))};if(Nf($.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(nh($)).map((Y)=>({type:2,value:Y}))}}async function gh($,w){let A=dh({to:$,verbose:w}),J=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(J.map((U)=>Kf(U,w)))}async function lh($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),$w.platform==="darwin"){if(w?.serverName)return yf($,w.serverName,{verbose:w.verbose});return EU($,{verbose:w.verbose})}else if($w.platform==="win32")try{let J=F1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!J)return z("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(F1(U).toString().includes(J))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if($w.platform==="linux")try{let J=F1(`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(F1(`find ${Y} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${J}"`).toString().includes(J))return z("ssl",`Certificate fingerprint found in ${Y}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${$w.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var ww=null,t7="rpx-root-ca.crt",p7="rpx-root-ca.key";var hU=X$(()=>{OB();p0();Q8();Lf();U$();Lf();x8()});function v1($,w){return async(A)=>{let J=new URL(A.url),Y=(A.headers.get("host")||"").split(":")[0],f=$(Y);if(!f)return z("request",`No route found for host: ${Y}`,w),new Response(`No proxy configured for ${Y}`,{status:404});let W=f.sourceHost,Z=J.pathname,E=Rf(J.pathname,f.pathRewrites);if(E)W=E.targetHost,Z=E.targetPath,z("request",`Path rewrite: ${J.pathname} → ${W}${Z}`,w);let B=`http://${W}${Z}${J.search}`;try{let h=new Headers(A.headers);if(h.set("host",W),f.changeOrigin)h.set("origin",`http://${f.sourceHost}`);h.set("x-forwarded-for","127.0.0.1"),h.set("x-forwarded-proto","https"),h.set("x-forwarded-host",Y);let j=await fetch(B,{method:A.method,headers:h,body:A.body,redirect:"manual"});if(f.cleanUrls&&J.pathname.endsWith(".html")){let T=J.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:T}})}let F=new Headers(j.headers);return new Response(j.body,{status:j.status,statusText:j.statusText,headers:F})}catch(h){return z("request",`Proxy error for ${Y}: ${h}`,w),new Response(`Proxy Error: ${h}`,{status:502})}}}var FU=X$(()=>{U$();U$()});import*as jU from"node:fs";import*as i$ from"node:fs/promises";import{homedir as s7}from"node:os";import*as Vf from"node:path";import*as zU from"node:process";function Aw(){return Vf.join(s7(),".stacks","rpx","registry.d")}function n1($){return typeof $==="string"&&$.length>0&&$.length<=128&&o7.test($)}function Of($,w){if(!n1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return Vf.join($,`${w}.json`)}function p$($){if(!Number.isInteger($)||$<=0)return!1;try{return zU.kill($,0),!0}catch(w){return w.code==="EPERM"}}function th($){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"&&n1(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 e7($){await i$.mkdir($,{recursive:!0})}async function ph($,w=Aw(),A){if(!th($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await e7(w);let J=Of(w,$.id),U=`${J}.tmp.${zU.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await i$.writeFile(U,Y,{encoding:"utf8",mode:420}),await i$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await i$.unlink(U).catch(()=>{}),f}}async function Xf($,w=Aw(),A){let J=Of(w,$);try{await i$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function $q($,w=Aw(),A){let J=Of(w,$);try{let U=await i$.readFile(J,"utf8"),Y=JSON.parse(U);if(!th(Y))return z("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 z("registry",`entry ${$} has invalid JSON, removing`,A),await i$.unlink(J).catch(()=>{}),null;throw U}}async function Fw($=Aw(),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(!n1(Y))continue;let f=await $q(Y,$,w);if(f)J.push(f)}return J}async function HU($=Aw(),w){let A=await Fw($,w),J=0;for(let U of A){if(U.pid===void 0)continue;if(!p$(U.pid))z("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await Xf(U.id,$,w).catch(()=>{}),J++}return J}function _f($,w={}){let A=w.dir??Aw(),J=w.debounceMs??100,U=w.pollMs??Math.max(J*2,250),Y=w.verbose;jU.mkdirSync(A,{recursive:!0});let f=null,W=!1,Z=null,E=!1,B=(G)=>{return JSON.stringify(G.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)))},h=()=>{if(f=null,W)return;Fw(A,Y).then((G)=>{return Z=B(G),$(G)}).catch((G)=>{z("registry",`watcher onChange failed: ${G}`,Y)})},j=()=>{if(W)return;if(f)clearTimeout(f);f=setTimeout(h,J)},T=setInterval(()=>{if(W||E)return;E=!0,Fw(A,Y).then((G)=>{if(B(G)!==Z)j()}).catch((G)=>{z("registry",`watcher poll failed: ${G}`,Y)}).finally(()=>{E=!1})},U),H=jU.watch(A,{persistent:!0},(G,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;j()});return H.on("error",(G)=>{z("registry",`watcher error: ${G}`,Y)}),j(),{close:()=>{if(W=!0,f)clearTimeout(f);clearInterval(T),H.close()}}}var o7;var m1=X$(()=>{U$();o7=/^[a-zA-Z0-9._-]+$/});import{spawn as wq}from"node:child_process";import*as jw from"node:fs/promises";import{homedir as Aq}from"node:os";import*as d1 from"node:path";import*as r$ from"node:process";function n0(){return d1.join(Aq(),".stacks","rpx")}function ah($=n0()){return d1.join($,"daemon.pid")}async function rh($=n0()){try{let w=await jw.readFile(ah($),"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 Jq($=n0()){await jw.unlink(ah($)).catch(()=>{})}function Uq(){let $=r$.execPath,w=d1.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&r$.argv[1])return[$,r$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function sh($={}){let w=$.rpxDir??n0(),A=$.verbose??!1;await Jw({rpxDir:w,verbose:A}).catch((B)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${B}`,A)});let J=await rh(w);if(J!==null&&p$(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await Jq(w);await jw.mkdir(w,{recursive:!0});let U=$.spawnCommand??Uq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=wq(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??r$.cwd(),env:$.spawnEnv?{...r$.env,...$.spawnEnv}:r$.env});Y.unref();let f=null;Y.once("error",(B)=>{f=B});let W=$.startupTimeoutMs??5000,Z=$.pollIntervalMs??50,E=Date.now()+W;while(Date.now()<E){if(f)throw f;let B=await rh(w);if(B!==null&&p$(B))return z("daemon",`daemon registered with pid=${B}`,A),{pid:B,spawned:!0};await new Promise((h)=>setTimeout(h,Z))}if(f)throw f;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var Df=X$(()=>{p0();hU();FU();m1();z1();U$()});import*as Uw from"node:fs/promises";import{homedir as Yq}from"node:os";import*as kf from"node:path";function eh(){return kf.join(Yq(),".stacks","rpx")}function Qf($=eh()){return kf.join($,fq)}async function GU($=eh()){try{let w=await Uw.readFile(Qf($),"utf8"),A=JSON.parse(w);if(A.version!==TU||!Array.isArray(A.resolvers))return null;return{version:TU,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 $F($,w){await Uw.mkdir($,{recursive:!0}),await Uw.writeFile(Qf($),`${JSON.stringify(w,null,2)}
|
|
200
|
+
`,"utf8")}async function xf($){await Uw.rm(Qf($),{force:!0})}function wF($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;return w}function Zq($){let w=wF($);if(!w)return null;let A=w.split(".");if(A.length<2)return null;return A.slice(-2).join(".")}function Pf($){let w=new Set;for(let A of $){let J=Zq(A);if(J)w.add(J)}return Array.from(w).sort()}function bf($){let w=new Set;for(let A of $){let J=wF(A);if(J)w.add(J)}return Array.from(w).sort()}var TU=1,fq="dns-state.json",oh;var AF=X$(()=>{oh=["com","test","dev","app","page","local","localhost","example","invalid"]});var KU={};JZ(KU,{tearDownDevelopmentDns:()=>zw,syncDevelopmentDnsFromRegistry:()=>g1,stopDnsServer:()=>cf,startDnsServer:()=>WF,setupResolver:()=>qq,setupDevelopmentDns:()=>mf,resolverFilePath:()=>H1,removeResolver:()=>Rq,removeLegacyTldResolvers:()=>nf,reconcileStaleDevelopmentDns:()=>Jw,isDnsServerRunning:()=>jq,contentLooksLikeRpxResolver:()=>EF,RPX_RESOLVER_MARKER:()=>YF,DNS_PORT:()=>RU});import Wq from"node:dgram";import*as JF from"node:fs/promises";import*as UF from"node:path";import*as m0 from"node:process";function Eq($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function ZF($,w){let A=[],J=w;while(!0){let U=$[J];if(U===0){J++;break}if((U&192)===192){let Y=$.readUInt16BE(J)&16383,{name:f}=ZF($,Y);A.push(f),J+=2;break}J++,A.push($.subarray(J,J+U).toString("ascii")),J+=U}return{name:A.join("."),newOffset:J}}function Bq($,w){let{name:A,newOffset:J}=ZF($,w),U=$.readUInt16BE(J),Y=$.readUInt16BE(J+2);return{question:{name:A,type:U,class:Y},newOffset:J+4}}function NU($){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 hq($,w,A){let J=[],U=Buffer.alloc(12);U.writeUInt16BE($,0),U.writeUInt16BE(33152,2),U.writeUInt16BE(1,4),U.writeUInt16BE(1,6),U.writeUInt16BE(0,8),U.writeUInt16BE(0,10),J.push(U),J.push(NU(w.name));let Y=Buffer.alloc(4);Y.writeUInt16BE(w.type,0),Y.writeUInt16BE(w.class,2),J.push(Y),J.push(NU(w.name));let f=Buffer.alloc(10);if(f.writeUInt16BE(w.type,0),f.writeUInt16BE(1,2),f.writeUInt32BE(300,4),w.type===1){f.writeUInt16BE(4,8),J.push(f);let W=A.split(".").map((Z)=>Number.parseInt(Z,10));J.push(Buffer.from(W))}else if(w.type===28)f.writeUInt16BE(16,8),J.push(f),J.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return U.writeUInt16BE(33155,2),U.writeUInt16BE(0,6),Buffer.concat([U,NU(w.name),Y]);return Buffer.concat(J)}function Fq($,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(NU(w.name));let U=Buffer.alloc(4);return U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),A.push(U),Buffer.concat(A)}async function WF($,w){if(m0.platform!=="darwin")return!1;let A=bf($);if(A.length===0)return!1;if(v$){for(let J of A)qU.add(J);return z("dns","DNS server already running — merged domains",w),!0}return qU=new Set(A),new Promise((J)=>{v$=Wq.createSocket("udp4"),v$.on("error",(U)=>{z("dns",`DNS server error: ${U.message}`,w),v$?.close(),v$=null,J(!1)}),v$.on("message",(U,Y)=>{try{let f=Eq(U),{question:W}=Bq(U,12);z("dns",`Query for ${W.name} type ${W.type} from ${Y.address}`,w);let Z=W.name.toLowerCase(),E=!1;for(let h of qU)if(Z===h||Z.endsWith(`.${h}`)){E=!0;break}let B;if(E&&(W.type===1||W.type===28))B=hq(f.id,W,"127.0.0.1"),z("dns",`Responding with localhost for ${W.name}`,w);else B=Fq(f.id,W),z("dns",`NXDOMAIN for ${W.name}`,w);v$?.send(B,Y.port,Y.address)}catch(f){z("dns",`Error processing DNS query: ${f}`,w)}}),v$.on("listening",()=>{let U=v$?.address();z("dns",`DNS server listening on ${U?.address}:${U?.port}`,w),J(!0)});try{v$.bind(RU,"127.0.0.1")}catch(U){z("dns",`Failed to bind DNS server: ${U}`,w),J(!1)}})}function cf($){if(v$)z("dns","Stopping DNS server",$),v$.close(),v$=null,qU=new Set}function jq(){return v$!==null}function zq(){return`${YF}
|
|
201
201
|
nameserver 127.0.0.1
|
|
202
202
|
port ${RU}
|
|
203
|
-
`}function H1($){return UF.join(fF,$)}function EF($){return $.includes("127.0.0.1")&&$.includes(String(RU))}async function
|
|
203
|
+
`}function H1($){return UF.join(fF,$)}function EF($){return $.includes("127.0.0.1")&&$.includes(String(RU))}async function Hq($){try{return await JF.readFile(H1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function uf($){if(m0.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A}=await Promise.resolve().then(() => (U$(),E1));if(!A()){z("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),z("dns","DNS cache flushed",$)}catch(J){z("dns",`Could not flush DNS cache: ${J}`,$)}}async function Tq($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (U$(),E1)),J=zq().replace(/\n/g,"\\n"),U=`bash -c 'mkdir -p ${fF} && printf "%b" "${J}" > ${H1($)}'`;A(U),z("dns",`Created ${H1($)}`,w)}async function Gq($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (U$(),E1));A(`rm -f ${H1($)}`),z("dns",`Removed ${H1($)}`,w)}async function qq($,w){return mf({domains:w??[],verbose:$})}async function Nq($,w){if(m0.platform!=="darwin")return!0;let{getSudoPassword:A}=await Promise.resolve().then(() => (U$(),E1));if(!A())return z("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let J of $)await Tq(J,w);return await uf(w),!0}catch(J){return z("dns",`Failed to create resolver file: ${J}`,w),!1}}async function vf($,w){if(m0.platform!=="darwin")return;let{getSudoPassword:A}=await Promise.resolve().then(() => (U$(),E1));if(!A())return;try{for(let J of $)await Gq(J,w);await uf(w)}catch(J){z("dns",`Failed to remove resolver files: ${J}`,w)}}async function nf($){if(m0.platform!=="darwin")return[];let w=[];for(let A of oh){let J=await Hq(A);if(J&&EF(J))await vf([A],$),w.push(A)}return w}async function mf($){let w=$.rpxDir??n0(),A=bf($.domains);if(A.length===0)return!1;let J=Pf(A);if(!await WF(A,$.verbose))return!1;if(!await Nq(J,$.verbose))return!1;let f={version:TU,resolvers:J,domains:A,ownerPid:$.ownerPid??m0.pid,updatedAt:new Date().toISOString()};return await $F(w,f),!0}async function g1($,w={}){let A=$.map((Z)=>Z.to).filter(Boolean),J=w.rpxDir??n0(),U=Pf(A),W=((await GU(J))?.resolvers??[]).filter((Z)=>!U.includes(Z));if(W.length>0)await vf(W,w.verbose);if(U.length===0){cf(w.verbose),await xf(J);return}await mf({domains:A,rpxDir:J,verbose:w.verbose,ownerPid:w.ownerPid??m0.pid})}async function zw($={}){let w=$.rpxDir??n0();cf($.verbose);let J=(await GU(w))?.resolvers??[];await vf(J,$.verbose),await nf($.verbose),await xf(w)}async function Rq($){await zw({verbose:$})}async function Jw($={}){let w=$.rpxDir??n0(),A=await GU(w),J=A?.ownerPid!=null&&p$(A.ownerPid);if(A&&!J){z("dns",`reconcile: owner pid ${A.ownerPid} is gone — tearing down DNS`,$.verbose),await zw($);return}let U=await nf($.verbose);if(U.length>0)z("dns",`reconcile: removed legacy TLD resolvers: ${U.join(", ")}`,$.verbose);await uf($.verbose)}var RU=15353,YF="# managed-by: rpx",fF="/etc/resolver",v$=null,qU;var z1=X$(()=>{Df();AF();m1();U$();qU=new Set});import{dirname as mq,join as dq}from"path";import*as u$ from"process";import{fileURLToPath as gq}from"url";import{existsSync as uF}from"node:fs";import kU from"node:fs/promises";import UZ from"node:os";import QU from"node:path";import Yw from"node:process";import{EventEmitter as vF}from"node:events";import d0 from"node:process";import YZ from"node:process";import iU from"node:process";import AA from"node:process";import N1 from"node:process";import WZ from"node:tty";import Vj,{stdin as h5,stdout as F5}from"node:process";import BZ,{stdin as _j,stdout as Dj}from"node:process";import kj from"node:readline";class FZ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=UZ.homedir(),w=QU.join($,".config","clapp");this.configPath=QU.join(w,"telemetry.json")}async isEnabled(){if(Yw.env.DO_NOT_TRACK==="1"||Yw.env.DO_NOT_TRACK==="true")return!1;if(Yw.env.NO_TELEMETRY==="1"||Yw.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:UZ.platform(),nodeVersion:Yw.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:Yw.env.DO_NOT_TRACK==="1"||Yw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(uF(this.configPath)){let $=await kU.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=QU.dirname(this.configPath);await kU.mkdir(w,{recursive:!0}),await kU.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 eq=new FZ;function nF($,w={}){let A={_:[]},J=w.alias||{},U=new Set(w.boolean||[]),Y={};for(let W of Object.keys(J))for(let Z of J[W])Y[Z]=W;for(let W of U)if(J[W])for(let Z of J[W])U.add(Z);function f(W,Z){let E=Y[W]||W;if(A[E]=Z,J[E])for(let B of J[E])A[B]=Z;if(Y[W]&&J[Y[W]])for(let B of J[Y[W]])A[B]=Z;A[W]=Z}for(let W=0;W<$.length;W++){let Z=$[W];if(Z==="--"){A._.push(...$.slice(W+1));break}if(Z.startsWith("--")){let E=Z.indexOf("=");if(E!==-1){let B=Z.slice(2,E),h=Z.slice(E+1);f(B,h)}else{let B=Z.slice(2);if(B.startsWith("no-")){let j=B.slice(3);f(j,!1);continue}let h=Y[B]||B;if(U.has(h)||U.has(B))f(B,!0);else{let j=$[W+1];if(j!==void 0&&!j.startsWith("-"))f(B,j),W++;else f(B,!0)}}}else if(Z.startsWith("-")&&Z.length>1){let E=Z.slice(1);for(let B=0;B<E.length;B++){let h=E[B],j=Y[h]||h;if(B===E.length-1&&!U.has(j)&&!U.has(h)){let F=$[W+1];if(F!==void 0&&!F.startsWith("-"))f(h,F),W++;else f(h,!0)}else f(h,!0)}}else A._.push(Z)}return A}function bU($){return $.replace(/[<[].+/,"").trim()}function mF($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,J=[],U=(W)=>{let Z=!1,E=W[1];if(E.startsWith("..."))E=E.slice(3),Z=!0;return{required:W[0].startsWith("<"),value:E,variadic:Z}},Y;while(Y=w.exec($))J.push(U(Y));let f;while(f=A.exec($))J.push(U(f));return J}function dF($){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((Y,f)=>{return f!==A&&Y.names.some((W)=>J.names.includes(W))&&typeof Y.required==="boolean"}))w.boolean.push(J.names[0])}else w.boolean.push(J.names[0])}return w}function fZ($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function xU($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function gF($){return $.replace(/([a-z])-([a-z])/g,(w,A,J)=>{return A+J.toUpperCase()})}function lF($,w,A){let J=0,U=w.length,Y=$,f;for(;J<U;++J)f=Y[w[J]],Y=Y[w[J]]=J===U-1?A:f!=null?f:!!~w[J+1].indexOf(".")||!(+w[J+1]>-1)?{}:[]}function tF($,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 pF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function jZ($){return $.split(".").map((w,A)=>{return A===0?gF(w):w}).join(".")}class wA 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
|
|
206
|
+
${this.stack}`;return this.message}}function rF(){let{env:$}=YZ,{TERM:w,TERM_PROGRAM:A}=$;if(YZ.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 YA="\x1B",A$=`${YA}[`;var N0={to($,w){if(!w)return`${A$}${$+1}G`;return`${A$}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${A$}${-$}D`;else if($>0)A+=`${A$}${$}C`;if(w<0)A+=`${A$}${-w}A`;else if(w>0)A+=`${A$}${w}B`;return A},up:($=1)=>`${A$}${$}A`,down:($=1)=>`${A$}${$}B`,forward:($=1)=>`${A$}${$}C`,backward:($=1)=>`${A$}${$}D`,nextLine:($=1)=>`${A$}E`.repeat($),prevLine:($=1)=>`${A$}F`.repeat($),left:`${A$}G`,hide:`${A$}?25l`,show:`${A$}?25h`,save:`${YA}7`,restore:`${YA}8`};var PU={screen:`${A$}2J`,up:($=1)=>`${A$}1J`.repeat($),down:($=1)=>`${A$}J`.repeat($),line:`${A$}2K`,lineEnd:`${A$}K`,lineStart:`${A$}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?N0.up():"");if($)w+=N0.left;return w}},J5={screen:`${YA}c`};function aF($,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 U=1;U<=$.length;U++)if(w.charAt(J-1)===$.charAt(U-1))A[J][U]=A[J-1][U-1];else A[J][U]=Math.min(A[J-1][U-1]+1,A[J][U-1]+1,A[J-1][U]+1);return A[w.length][$.length]}function zZ($,w,A=2,J=3){return w.map((U)=>({cmd:U,distance:aF($,U)})).filter(({distance:U})=>U<=A).sort((U,Y)=>U.distance-Y.distance).slice(0,J).map(({cmd:U})=>U)}class HZ{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=bU($).split(",").map((J)=>{let U=J.trim().replace(/^-{1,2}/,"");if(U.startsWith("no-"))this.negated=!0,U=U.replace(/^no-/,"");return jZ(U)}).sort((J,U)=>J.length>U.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 Y5=iU.argv,sF=`${iU.platform}-${iU.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,ZZ=AA.argv,oF=`${AA.platform}-${AA.arch} node-${AA.version}`;class cU{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=bU($);let U=bU($),Y=U.indexOf(":");if(Y>0)this.namespace=U.substring(0,Y),this.name=U.substring(Y+1);if(this.args=mF($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!A)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,A){let J=new HZ($,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 uU}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:U}=this.cli.globalCommand,Y=[{body:`${$}${A?`/${A}`:""}`}];if(Y.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let Z=fZ(w.map((F)=>F.rawName)),E=new Map,B=[];for(let F of w)if(F.namespace){if(!E.has(F.namespace))E.set(F.namespace,[]);E.get(F.namespace).push(F)}else B.push(F);let h="";if(B.length>0)h+=B.map((F)=>{return` ${xU(F.rawName,Z.length)} ${F.description}`}).join(`
|
|
207
207
|
`);let j=Array.from(E.keys()).sort();for(let F of j){let T=E.get(F);if(h.length>0)h+=`
|
|
208
208
|
|
|
209
209
|
`;h+=` ${F}:
|
|
@@ -214,7 +214,7 @@ ${this.stack}`;return this.message}}function pF(){let{env:$}=YZ,{TERM:w,TERM_PRO
|
|
|
214
214
|
`)});if(U)Y=U(Y)||Y;console.log(Y.map((Z)=>{return Z.title?`${Z.title}:
|
|
215
215
|
${Z.body}`:Z.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"?sF:oF}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((U)=>U.required).slice(this.cli.args.length),J=A.map((U)=>`<${U.value}>`).join(" ");throw new wA(`Missing required argument${A.length>1?"s":""}: ${J}
|
|
218
218
|
|
|
219
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 U=[...w.options,...this.options].flatMap((Z)=>Z.names),Y=A.length>1?`--${A}`:`-${A}`,f=zZ(A,U),W=`Unknown option \`${Y}\``;if(f.length>0)W+=`
|
|
220
220
|
|
|
@@ -223,27 +223,27 @@ Did you mean one of these?`,f.forEach((Z)=>{let E=Z.length>1?`--${Z}`:`-${Z}`;W+
|
|
|
223
223
|
|
|
224
224
|
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new wA(W)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let J of A){let U=$[J.name.split(".")[0]];if(J.required){let Y=A.some((f)=>f.negated&&f.names.includes(J.name));if(U===!0||U===!1&&!Y)throw new wA(`Option \`${J.rawName}\` requires a value.
|
|
225
225
|
|
|
226
|
-
Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class uU extends cU{constructor($){super("@@global@@","",{},$)}}var
|
|
226
|
+
Example: ${this.cli.name} ${this.rawName} ${J.rawName} <value>`)}}}}class uU extends cU{constructor($){super("@@global@@","",{},$)}}var eF=cU,g0={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 G1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function $j(){return!0}function wj(){let $={};$.supportsColor=$j();function w(J,U=[]){let Y=J===""?[]:[...U,J],f=function(Z){if(!$.supportsColor)return Z;let E="",B="";for(let h of Y)if(h in G1&&G1[h]in g0){let j=G1[h];E+=g0[j][0],B=g0[j][1]+B}else if(h in g0)E+=g0[h][0],B=g0[h][1]+B;return E+Z+B},W=[...Object.keys(g0),...Object.keys(G1)];for(let Z of W)if(!(Z in f))Object.defineProperty(f,Z,{get(){return w(Z,Y)}});return f}let A=[...Object.keys(g0),...Object.keys(G1)];for(let J of A)if(!(J in $))Object.defineProperty($,J,{get(){return w(J)}});return $}var q1=wj();class vU extends vF{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 uU(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)}d0.exit(0)};return d0.on("SIGINT",()=>w("SIGINT")),d0.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
|
|
228
|
+
Received ${A}, cleaning up...`),$)try{await $()}catch(J){console.error("Error during cleanup:",J)}d0.exit(0)};return d0.on("SIGINT",()=>w("SIGINT")),d0.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 eF($,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(q1.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=zZ($,w);if(A.length>0)console.log(q1.yellow("Did you mean one of these?")),A.forEach((J)=>console.log(` ${q1.dim("•")} ${this.name} ${J}`)),console.log("")}console.log(q1.dim("Run"),`${this.name} --help`,q1.dim("to see all available commands")),d0.exit(1)}async parse($=ZZ,w={}){let{run:A=!0,exitOnError:J=!1}=w;if(J)try{return await this.parse($,{run:A})}catch(Z){throw this.handleUsageError(Z),Z}if(this.rawArgs=$,!this.name)this.name=$[1]?
|
|
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=zZ($,w);if(A.length>0)console.log(q1.yellow("Did you mean one of these?")),A.forEach((J)=>console.log(` ${q1.dim("•")} ${this.name} ${J}`)),console.log("")}console.log(q1.dim("Run"),`${this.name} --help`,q1.dim("to see all available commands")),d0.exit(1)}async parse($=ZZ,w={}){let{run:A=!0,exitOnError:J=!1}=w;if(J)try{return await this.parse($,{run:A})}catch(Z){throw this.handleUsageError(Z),Z}if(this.rawArgs=$,!this.name)this.name=$[1]?pF($[1]):"cli";let U=!0,Y=$.slice(2),f=Y[0];if(f&&!f.startsWith("-")){for(let Z of this.commands)if(Z.isMatched(f)){let E=this.mri(Y,Z);U=!1;let B={...E,args:E.args.slice(1)};this.setParsedInfo(B,Z,f),this.emit(`command:${f}`,Z);break}}if(U){for(let Z of this.commands)if(Z.name===""){U=!1;let E=this.mri(Y,Z);this.setParsedInfo(E,Z),this.emit("command:!",Z);break}}if(U){let Z=this.mri($.slice(2));this.setParsedInfo(Z)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),A=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),A=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(A)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return W}mri($,w){let A=[...this.globalCommand.options,...w?w.options:[]],J=dF(A),U=[],Y=$.indexOf("--");if(Y>-1)U=$.slice(Y+1),$=$.slice(0,Y);let f=nF($,J),W={_:f._};for(let j of Object.keys(f))if(j!=="_")W[jZ(j)]=f[j];let Z=W._,E={"--":U},B=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,h=Object.create(null);for(let j of A){if(!B&&j.config.default!==void 0)for(let F of j.names)E[F]=j.config.default;if(Array.isArray(j.config.type)){if(h[j.name]===void 0)h[j.name]={shouldTransform:!0,transformFunction:j.config.type[0]}}}for(let j of Object.keys(W))if(j!=="_"){let F=j.split(".");lF(E,F,W[j]),tF(E,h)}return{args:Z,options:E}}async run($=ZZ){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let J=$,U=J.message??"command-line error",Y=this.name?`${this.name}: `:"",f=/--help/.test(U)?"":`
|
|
231
231
|
Run \`${this.name??"cli"} --help\` for usage.`;d0.stderr.write(`${Y}${U}${f}
|
|
232
|
-
`),d0.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((W,Z)=>{if(W.variadic)J.push($.slice(Z));else J.push($[Z])}),J.push(w);let U={command:A,args:J,options:w};for(let W of A.beforeHooks)await W(U);let Y,f=async()=>{let W=A.commandAction.apply(this,J);if(W instanceof Promise)Y=await W;else Y=W;return Y};if(A.middleware.length>0){let W=0,Z=async()=>{if(W<A.middleware.length){let E=A.middleware[W++];await E({...U,next:Z})}else await f()};await Z()}else await f();for(let W of A.afterHooks)await W(U);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return d0.removeAllListeners("SIGINT"),d0.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 TZ{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
|
|
232
|
+
`),d0.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((W,Z)=>{if(W.variadic)J.push($.slice(Z));else J.push($[Z])}),J.push(w);let U={command:A,args:J,options:w};for(let W of A.beforeHooks)await W(U);let Y,f=async()=>{let W=A.commandAction.apply(this,J);if(W instanceof Promise)Y=await W;else Y=W;return Y};if(A.middleware.length>0){let W=0,Z=async()=>{if(W<A.middleware.length){let E=A.middleware[W++];await E({...U,next:Z})}else await f()};await Z()}else await f();for(let W of A.afterHooks)await W(U);return Y}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return d0.removeAllListeners("SIGINT"),d0.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 TZ{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 Z5=new TZ;function Aj(){if("FORCE_COLOR"in N1.env)return N1.env.FORCE_COLOR!=="0";if("NO_COLOR"in N1.env||N1.env.TERM==="dumb")return!1;if(N1.platform==="win32")return!0;return WZ.isatty(1)&&WZ.isatty(2)}var GZ=Aj();function s($,w){if(!GZ)return(A)=>A;return(A)=>$+A+w}var Jj=s("\x1B[0m","\x1B[0m"),Uj=s("\x1B[31m","\x1B[39m"),Yj=s("\x1B[32m","\x1B[39m"),fj=s("\x1B[33m","\x1B[39m"),Zj=s("\x1B[34m","\x1B[39m"),Wj=s("\x1B[35m","\x1B[39m"),Ej=s("\x1B[36m","\x1B[39m"),Bj=s("\x1B[37m","\x1B[39m"),hj=s("\x1B[90m","\x1B[39m"),Fj=s("\x1B[1m","\x1B[22m"),jj=s("\x1B[3m","\x1B[23m"),zj=s("\x1B[4m","\x1B[24m"),Hj=s("\x1B[2m","\x1B[22m"),Tj=s("\x1B[7m","\x1B[27m"),Gj=s("\x1B[8m","\x1B[28m"),qj=s("\x1B[9m","\x1B[29m"),Nj=s("\x1B[41m","\x1B[49m"),Rj=s("\x1B[42m","\x1B[49m"),Kj=s("\x1B[43m","\x1B[49m"),Mj=s("\x1B[44m","\x1B[49m"),Ij=s("\x1B[45m","\x1B[49m"),Cj=s("\x1B[46m","\x1B[49m"),yj=s("\x1B[47m","\x1B[49m"),Lj=GZ,Sj={reset:Jj,red:Uj,green:Yj,yellow:fj,blue:Zj,magenta:Wj,cyan:Ej,white:Bj,gray:hj,bold:Fj,italic:jj,underline:zj,dim:Hj,inverse:Tj,hidden:Gj,strikethrough:qj,bgRed:Nj,bgGreen:Rj,bgYellow:Kj,bgBlue:Mj,bgMagenta:Ij,bgCyan:Cj,bgWhite:yj,isColorSupported:Lj},JA=Sj,Oj=["up","down","left","right","space","enter","cancel"],UA={actions:new Set(Oj),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function qZ($,w){if(typeof $==="string")return UA.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(qZ(A,w))return!0}return!1}function Xj($,w){if($===w)return[];let A=$.split(`
|
|
233
233
|
`),J=w.split(`
|
|
234
|
-
`),U=[];for(let Y=0;Y<Math.max(A.length,J.length);Y++)if(A[Y]!==J[Y])U.push(Y);return U}var
|
|
235
|
-
`),f=[];for(let W of Y){if(
|
|
236
|
-
`)}class nU{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=
|
|
234
|
+
`),U=[];for(let Y=0;Y<Math.max(A.length,J.length);Y++)if(A[Y]!==J[Y])U.push(Y);return U}var j5=Vj.platform.startsWith("win"),EZ=Symbol("clapp:cancel");function $A($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function Qj($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function xj($){return Qj($).length}function hZ($,w,A){if(!w||w<1)return $;let J=A?.hard??!1,U=A?.trim??!0,Y=$.split(`
|
|
235
|
+
`),f=[];for(let W of Y){if(xj(W)<=w){f.push(U?W.trimEnd():W);continue}if(J){let Z="",E=0,B=0;while(B<W.length){let h=W.slice(B).match(/^\x1b\[[0-9;]*m/);if(h){Z+=h[0],B+=h[0].length;continue}if(E>=w)f.push(U?Z.trimEnd():Z),Z="",E=0;Z+=W[B],E++,B++}if(Z)f.push(U?Z.trimEnd():Z)}else f.push(U?W.trimEnd():W)}return f.join(`
|
|
236
|
+
`)}class nU{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=_j,output:J=Dj,render:U,signal:Y,...f}=$;this.opts=f,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=U.bind(this),this._track=w,this._abortSignal=Y,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 U of A)if(U.cb(...w),U.once)J.push(()=>A.splice(A.indexOf(U),1));for(let U of J)U();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(EZ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=kj.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),$A(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(N0.show),this.output.off("resize",this.render),$A(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(N0.show),this.output.off("resize",this.render),$A(this.input,!1),$(EZ)})})}_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&&UA.aliases.has(w.name))this.emit("cursor",UA.aliases.get(w.name));if(UA.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(qZ([$,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
237
|
`),$A(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 $=hZ(this._prevFrame,BZ.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
238
|
-
`).length-1;this.output.write(N0.move(-999,$*-1))}render(){let $=hZ(this._render(this)??"",BZ.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(N0.hide);else{let w=
|
|
238
|
+
`).length-1;this.output.write(N0.move(-999,$*-1))}render(){let $=hZ(this._render(this)??"",BZ.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(N0.hide);else{let w=Xj(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(N0.move(0,A)),this.output.write(PU.lines(1));let J=$.split(`
|
|
239
239
|
`);this.output.write(J[A]),this._prevFrame=$,this.output.write(N0.move(0,J.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(N0.move(0,A)),this.output.write(PU.down());let U=$.split(`
|
|
240
240
|
`).slice(A);this.output.write(U.join(`
|
|
241
|
-
`)),this._prevFrame=$;return}this.output.write(PU.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function
|
|
242
|
-
`)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=await Hw($);if(A!==null&&t$(A))throw Error(`rpx daemon already running (pid=${A})`);await T0.unlink(w).catch(()=>{})}}async function l1($=U0()){await T0.unlink(Tw($)).catch(()=>{})}function Iq($){return{sourceHost:new URL($.from.startsWith("http")?$.from:`http://${$.from}`).host,cleanUrls:$.cleanUrls??!1,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites}}function Cq($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function yq($,w){let A=await Fw(w,$.verbose),J=[...new Set(A.map((B)=>B.to))],U=Cq(J),Y=[...new Set([U,...J,"rpx.localhost"])],f=z0.join(BF(),".stacks","ssl"),W=z0.join(f,"rpx.localhost.crt"),Z={https:typeof $.https==="object"?{...$.https,certPath:W,keyPath:z0.join(f,"rpx.localhost.key"),commonName:U}:{certPath:W,keyPath:z0.join(f,"rpx.localhost.key"),caCertPath:z0.join(f,"rpx.localhost.ca.crt"),commonName:U},verbose:$.verbose,regenerateUntrustedCerts:!0,...Y.length>1?{proxies:Y.map((B)=>({from:"localhost:1",to:B}))}:{to:U,from:"localhost:1"}},E=await v0(Z);if(!E)z("daemon","no usable cert on disk, generating one",$.verbose),await j1(Z),E=await v0(Z);if(!E)throw Error("failed to bootstrap TLS for rpx daemon");return E}async function hF($={}){let w=$.verbose??!1,A=$.rpxDir??U0(),J=$.registryDir??z0.join(A,"registry.d"),U=$.httpsPort??443,Y=$.httpPort??80,f=$.hostname??"0.0.0.0",W=$.gcIntervalMs??Kq,Z=await Mq(A),E=new Map,B=(L)=>E.get(L);function h(L){let f$=new Map;for(let H0 of L)f$.set(H0.to,Iq(H0));E=f$,z("daemon",`routing table now covers ${f$.size} host(s): ${Array.from(f$.keys()).join(", ")||"<empty>"}`,w)}await HU(J,w).catch((L)=>{z("daemon",`initial gc failed: ${L}`,w)});let j=await Fw(J,w);h(j),await Jw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS reconcile on start failed: ${L}`,w)}),await g1(j,{rpxDir:A,verbose:w,ownerPid:Y$.pid}).catch((L)=>{z("daemon",`DNS setup on start failed: ${L}`,w)});let F=await yq($,J),T=Bun.serve({port:U,hostname:f,tls:{key:F.key,cert:F.cert,ca:F.ca,requestCert:!1,rejectUnauthorized:!1},fetch:v1(B,w),error(L){return z("daemon",`https server error: ${L}`,w),new Response(`Server Error: ${L.message}`,{status:500})}}),H=null;if(Y>0)H=Bun.serve({port:Y,hostname:f,fetch(L){let f$=new URL(L.url),H0=(L.headers.get("host")??f$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${H0}${f$.pathname}${f$.search}`}})}});if(w)R.success(`rpx daemon listening on https://${f}:${U}${H?` (http→https on :${Y})`:""}`),R.info(`pid file: ${Z}`),R.info(`registry: ${J}`);let G=_f((L)=>{h(L),g1(L,{rpxDir:A,verbose:w,ownerPid:Y$.pid}).catch((f$)=>{z("daemon",`DNS sync on registry change failed: ${f$}`,w)})},{dir:J,verbose:w}),q=setInterval(()=>{HU(J,w).then((L)=>{if(L>0)z("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{z("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof q.unref==="function")q.unref();let N=!1,K,C=new Promise((L)=>{K=L});async function y(){if(N)return C;if(N=!0,clearInterval(q),G.close(),T.stop(!1),H?.stop(!1),await zw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS teardown failed: ${L}`,w)}),await l1(A),w)R.info("rpx daemon stopped");return K(),C}let S=(L)=>{z("daemon",`received ${L}, shutting down`,w),y().catch(()=>{})};return Y$.once("SIGINT",S),Y$.once("SIGTERM",S),{stop:y,done:C,httpsPort:typeof T.port==="number"?T.port:U,httpPort:H&&typeof H.port==="number"?H.port:Y,pidPath:Z}}function Lq(){let $=Y$.execPath,w=z0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&Y$.argv[1])return[$,Y$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function FF($={}){let w=$.rpxDir??U0(),A=$.verbose??!1;await Jw({rpxDir:w,verbose:A}).catch((B)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${B}`,A)});let J=await Hw(w);if(J!==null&&t$(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await l1(w);await T0.mkdir(w,{recursive:!0});let U=$.spawnCommand??Lq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=Rq(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??Y$.cwd(),env:$.spawnEnv?{...Y$.env,...$.spawnEnv}:Y$.env});Y.unref();let f=null;Y.once("error",(B)=>{f=B});let W=$.startupTimeoutMs??5000,Z=$.pollIntervalMs??50,E=Date.now()+W;while(Date.now()<E){if(f)throw f;let B=await Hw(w);if(B!==null&&t$(B))return z("daemon",`daemon registered with pid=${B}`,A),{pid:B,spawned:!0};await new Promise((h)=>setTimeout(h,Z))}if(f)throw f;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function jF($={}){let w=$.rpxDir??U0(),A=$.verbose??!1,J=$.timeoutMs??5000,U=$.pollIntervalMs??50,Y=$.forceAfterTimeout??!0,f=await Hw(w);if(f===null||!t$(f)){if(f!==null)await l1(w);return await Jw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:f,forced:!1}}try{Y$.kill(f,"SIGTERM")}catch(Z){if(Z.code==="ESRCH")return await l1(w),{stopped:!1,pid:f,forced:!1};throw Z}let W=Date.now()+J;while(Date.now()<W){if(!t$(f))return z("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`);z("daemon",`daemon pid=${f} did not exit, escalating to SIGKILL`,A);try{Y$.kill(f,"SIGKILL")}catch(Z){if(Z.code!=="ESRCH")throw Z}return await l1(w),await zw({rpxDir:w,verbose:A}).catch((Z)=>{z("daemon",`DNS teardown after SIGKILL: ${Z}`,A)}),{stopped:!0,pid:f,forced:!0}}async function zF($={}){let w=$.rpxDir??U0();if(await MU(w))return;await Jw({rpxDir:w,verbose:$.verbose})}p0();U$();import{spawn as Sq}from"node:child_process";import*as Gw from"node:process";class HF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Gw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${J0(w.env)}`,A);let f=Sq(J,U,{cwd:Y,env:{...Gw.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",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),Z(E),Gw.emit("SIGINT")}),f.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),Z(Error(`Process ${$} exited with code ${E}`)),Gw.emit("SIGINT")}),A)f.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),f.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),Z(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((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 IU=new HF;U$();import*as c$ from"node:fs/promises";import{homedir as Vq}from"node:os";import*as df from"node:path";import*as gf from"node:process";var Oq=/^[a-zA-Z0-9._-]+$/;function qw(){return df.join(Vq(),".stacks","rpx","registry.d")}function T1($){return typeof $==="string"&&$.length>0&&$.length<=128&&Oq.test($)}function lf($,w){if(!T1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return df.join($,`${w}.json`)}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"&&T1(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 Xq($){await c$.mkdir($,{recursive:!0})}async function GF($,w=qw(),A){if(!TF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Xq(w);let J=lf(w,$.id),U=`${J}.tmp.${gf.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await c$.writeFile(U,Y,{encoding:"utf8",mode:420}),await c$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await c$.unlink(U).catch(()=>{}),f}}async function qF($,w=qw(),A){let J=lf(w,$);try{await c$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function tf($,w=qw(),A){let J=lf(w,$);try{let U=await c$.readFile(J,"utf8"),Y=JSON.parse(U);if(!TF(Y))return z("registry",`entry ${$} failed validation, removing`,A),await c$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await c$.unlink(J).catch(()=>{}),null;throw U}}async function NF($=qw(),w){let A;try{A=await c$.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(!T1(Y))continue;let f=await tf(Y,$,w);if(f)J.push(f)}return J}p0();import{execSync as Pq}from"node:child_process";import*as Mw from"node:http";import*as LF from"node:http2";import*as SF from"node:net";import*as o from"node:process";var CU=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,G0={bold:CU(1,22),dim:CU(2,22),green:CU(32,39),cyan:CU(36,39)};Q8();Df();p0();m1();U$();import*as RF from"node:fs";import*as KF from"node:path";import*as q0 from"node:process";function _q($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function pf($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,U=$.proxies.map((j)=>{let F=j.id??_q(j.to);if(!n1(F))throw Error(`invalid registry id "${F}" derived from to="${j.to}"`);if(J.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return J.add(F),{...j,id:F}}),Y=new Date().toISOString();for(let j of U)await ph({id:j.id,from:j.from,to:j.to,pid:$.persistent?void 0:q0.pid,cwd:q0.cwd(),createdAt:Y,cleanUrls:j.cleanUrls,changeOrigin:j.changeOrigin,pathRewrites:j.pathRewrites},A,w);let f=await sh({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let j of U)R.success(`https://${j.to} → ${j.from}`);if(R.info(`(via rpx daemon pid=${f.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,Z=A??Aw(),E=U.map((j)=>j.id),B=async()=>{if(W)return;W=!0;for(let j of E)await Xf(j,A,w).catch((F)=>{z("runner",`removeEntry(${j}) failed: ${F}`,w)})},h=(j)=>{z("runner",`received ${j}, unregistering ${E.length} entries`,w),B().finally(()=>q0.exit(0))};q0.once("SIGINT",h),q0.once("SIGTERM",h),q0.once("exit",()=>{if(W)return;for(let j of E)try{RF.unlinkSync(KF.join(Z,`${j}.json`))}catch{}}),await new Promise(()=>{})}U$();import{exec as Dq}from"node:child_process";import Nw from"node:fs";import MF from"node:os";import af from"node:path";import*as t1 from"node:process";import{promisify as kq}from"node:util";var yU=kq(Dq),Y0=t1.platform==="win32"?af.join(t1.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",rf=!1;async function LU($){if(t1.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Bw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:U}=await yU(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return rf=!0,U}if(rf)try{let{stdout:U}=await yU(`sudo -n sh -c '${A}'`);return U}catch(U){z("hosts","Cached sudo privileges expired, requesting again",!0)}let{stdout:J}=await yU(`sudo sh -c '${A}'`);return rf=!0,J}catch(J){throw Error(`Failed to execute sudo command: ${J.message}`)}}async function p1($,w){z("hosts",`Adding hosts: ${$.join(", ")}`,w),z("hosts",`Using hosts file at: ${Y0}`,w);try{let A;try{A=await Nw.promises.readFile(Y0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await LU(`cat "${Y0}"`)}catch(f){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let J=$.filter((f)=>{let W=`127.0.0.1 ${f}`,Z=`::1 ${f}`;return!A.includes(W)&&!A.includes(Z)});if(J.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=J.map((f)=>`
|
|
241
|
+
`)),this._prevFrame=$;return}this.output.write(PU.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function Pj($,w){if($===void 0)return 0;if(w.length===0)return 0;let J=w.findIndex((U)=>U.value===$);return J!==-1?J:0}function bj($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function ij($,w){if(!w)return;if($)return w;return w[0]}class cj extends nU{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#J;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return JA.inverse(JA.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`${$}${JA.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??bj;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 U=w.findIndex((Y)=>Y.value===J);if(U!==-1)this.toggleSelected(J),this.#$=U}this.focusedValue=this.options[this.#$]?.value,this.on("key",(J,U)=>this.#U(J,U)),this.on("userInput",(J)=>this.#Y(J))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#U($,w){let A=w.name==="up",J=w.name==="down",U=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(U)this.value=ij(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=[$]}#Y($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#J($,A));else this.filteredOptions=[...w];if(this.#$=Pj(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 uj extends nU{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((U)=>U.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((U)=>({...U,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 vj=rF();var t=($,w)=>vj?$:w,T5=t("◆","*"),G5=t("■","x"),q5=t("▲","x"),N5=t("◇","o"),R5=t("┌","T"),nj=t("│","|"),K5=t("└","—"),M5=t("●",">"),I5=t("○"," "),C5=t("◻","[•]"),y5=t("◼","[+]"),L5=t("◻","[ ]"),S5=t("▪","•"),V5=t("─","-"),O5=t("╮","+"),X5=t("├","+"),_5=t("╯","+"),D5=t("●","•"),k5=t("◆","*"),Q5=t("▲","!"),x5=t("■","x");var P5={light:t("─","-"),heavy:t("━","="),block:t("█","#")};function mj(){return`${JA.gray(nj)} `}var b5=mj();XY();import{homedir as _Y}from"node:os";import{join as DY,resolve as LN}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",e9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:DY(_Y(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:DY(_Y(),".stacks","ssl","stacks.localhost.crt"),keyPath:DY(_Y(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Pw=e9;p0();hU();FU();m1();z1();U$();import{spawn as Kq}from"node:child_process";import*as T0 from"node:fs/promises";import{homedir as BF}from"node:os";import*as z0 from"node:path";import*as Y$ from"node:process";var Mq=5000;function U0(){return z0.join(BF(),".stacks","rpx")}function Tw($=U0()){return z0.join($,"daemon.pid")}async function Hw($=U0()){try{let w=await T0.readFile(Tw($),"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 MU($=U0()){let w=await Hw($);return w!==null&&p$(w)}async function Iq($=U0()){await T0.mkdir($,{recursive:!0});let w=Tw($);while(!0){try{let J=await T0.open(w,"wx");try{await J.write(`${Y$.pid}
|
|
242
|
+
`)}finally{await J.close()}return w}catch(J){if(J.code!=="EEXIST")throw J}let A=await Hw($);if(A!==null&&p$(A))throw Error(`rpx daemon already running (pid=${A})`);await T0.unlink(w).catch(()=>{})}}async function l1($=U0()){await T0.unlink(Tw($)).catch(()=>{})}function Cq($){return{sourceHost:new URL($.from.startsWith("http")?$.from:`http://${$.from}`).host,cleanUrls:$.cleanUrls??!1,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites}}function yq($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function Lq($,w){let A=await Fw(w,$.verbose),J=[...new Set(A.map((B)=>B.to))],U=yq(J),Y=[...new Set([U,...J,"rpx.localhost"])],f=z0.join(BF(),".stacks","ssl"),W=z0.join(f,"rpx.localhost.crt"),Z={https:typeof $.https==="object"?{...$.https,certPath:W,keyPath:z0.join(f,"rpx.localhost.key"),commonName:U}:{certPath:W,keyPath:z0.join(f,"rpx.localhost.key"),caCertPath:z0.join(f,"rpx.localhost.ca.crt"),commonName:U},verbose:$.verbose,regenerateUntrustedCerts:!0,...Y.length>1?{proxies:Y.map((B)=>({from:"localhost:1",to:B}))}:{to:U,from:"localhost:1"}},E=await v0(Z);if(!E)z("daemon","no usable cert on disk, generating one",$.verbose),await j1(Z),E=await v0(Z);if(!E)throw Error("failed to bootstrap TLS for rpx daemon");return E}async function hF($={}){let w=$.verbose??!1,A=$.rpxDir??U0(),J=$.registryDir??z0.join(A,"registry.d"),U=$.httpsPort??443,Y=$.httpPort??80,f=$.hostname??"0.0.0.0",W=$.gcIntervalMs??Mq,Z=await Iq(A),E=new Map,B=(L)=>E.get(L);function h(L){let f$=new Map;for(let H0 of L)f$.set(H0.to,Cq(H0));E=f$,z("daemon",`routing table now covers ${f$.size} host(s): ${Array.from(f$.keys()).join(", ")||"<empty>"}`,w)}await HU(J,w).catch((L)=>{z("daemon",`initial gc failed: ${L}`,w)});let j=await Fw(J,w);h(j),await Jw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS reconcile on start failed: ${L}`,w)}),await g1(j,{rpxDir:A,verbose:w,ownerPid:Y$.pid}).catch((L)=>{z("daemon",`DNS setup on start failed: ${L}`,w)});let F=await Lq($,J),T=Bun.serve({port:U,hostname:f,tls:{key:F.key,cert:F.cert,ca:F.ca,requestCert:!1,rejectUnauthorized:!1},fetch:v1(B,w),error(L){return z("daemon",`https server error: ${L}`,w),new Response(`Server Error: ${L.message}`,{status:500})}}),H=null;if(Y>0)H=Bun.serve({port:Y,hostname:f,fetch(L){let f$=new URL(L.url),H0=(L.headers.get("host")??f$.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${H0}${f$.pathname}${f$.search}`}})}});if(w)R.success(`rpx daemon listening on https://${f}:${U}${H?` (http→https on :${Y})`:""}`),R.info(`pid file: ${Z}`),R.info(`registry: ${J}`);let G=_f((L)=>{h(L),g1(L,{rpxDir:A,verbose:w,ownerPid:Y$.pid}).catch((f$)=>{z("daemon",`DNS sync on registry change failed: ${f$}`,w)})},{dir:J,verbose:w}),q=setInterval(()=>{HU(J,w).then((L)=>{if(L>0)z("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{z("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof q.unref==="function")q.unref();let N=!1,K,C=new Promise((L)=>{K=L});async function y(){if(N)return C;if(N=!0,clearInterval(q),G.close(),T.stop(!1),H?.stop(!1),await zw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS teardown failed: ${L}`,w)}),await l1(A),w)R.info("rpx daemon stopped");return K(),C}let S=(L)=>{z("daemon",`received ${L}, shutting down`,w),y().catch(()=>{})};return Y$.once("SIGINT",S),Y$.once("SIGTERM",S),{stop:y,done:C,httpsPort:typeof T.port==="number"?T.port:U,httpPort:H&&typeof H.port==="number"?H.port:Y,pidPath:Z}}function Sq(){let $=Y$.execPath,w=z0.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&Y$.argv[1])return[$,Y$.argv[1],"daemon:start"];return[$,"daemon:start"]}async function FF($={}){let w=$.rpxDir??U0(),A=$.verbose??!1;await Jw({rpxDir:w,verbose:A}).catch((B)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${B}`,A)});let J=await Hw(w);if(J!==null&&p$(J))return z("daemon",`ensureDaemonRunning: already running pid=${J}`,A),{pid:J,spawned:!1};if(J!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${J}`,A),await l1(w);await T0.mkdir(w,{recursive:!0});let U=$.spawnCommand??Sq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${U.join(" ")}`,A);let Y=Kq(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??Y$.cwd(),env:$.spawnEnv?{...Y$.env,...$.spawnEnv}:Y$.env});Y.unref();let f=null;Y.once("error",(B)=>{f=B});let W=$.startupTimeoutMs??5000,Z=$.pollIntervalMs??50,E=Date.now()+W;while(Date.now()<E){if(f)throw f;let B=await Hw(w);if(B!==null&&p$(B))return z("daemon",`daemon registered with pid=${B}`,A),{pid:B,spawned:!0};await new Promise((h)=>setTimeout(h,Z))}if(f)throw f;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function jF($={}){let w=$.rpxDir??U0(),A=$.verbose??!1,J=$.timeoutMs??5000,U=$.pollIntervalMs??50,Y=$.forceAfterTimeout??!0,f=await Hw(w);if(f===null||!p$(f)){if(f!==null)await l1(w);return await Jw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:f,forced:!1}}try{Y$.kill(f,"SIGTERM")}catch(Z){if(Z.code==="ESRCH")return await l1(w),{stopped:!1,pid:f,forced:!1};throw Z}let W=Date.now()+J;while(Date.now()<W){if(!p$(f))return z("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`);z("daemon",`daemon pid=${f} did not exit, escalating to SIGKILL`,A);try{Y$.kill(f,"SIGKILL")}catch(Z){if(Z.code!=="ESRCH")throw Z}return await l1(w),await zw({rpxDir:w,verbose:A}).catch((Z)=>{z("daemon",`DNS teardown after SIGKILL: ${Z}`,A)}),{stopped:!0,pid:f,forced:!0}}async function zF($={}){let w=$.rpxDir??U0();if(await MU(w))return;await Jw({rpxDir:w,verbose:$.verbose})}p0();U$();import{spawn as Vq}from"node:child_process";import*as Gw from"node:process";class HF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Gw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${J0(w.env)}`,A);let f=Vq(J,U,{cwd:Y,env:{...Gw.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",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),Z(E),Gw.emit("SIGINT")}),f.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),Z(Error(`Process ${$} exited with code ${E}`)),Gw.emit("SIGINT")}),A)f.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),f.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),Z(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((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 IU=new HF;U$();import*as c$ from"node:fs/promises";import{homedir as Oq}from"node:os";import*as df from"node:path";import*as gf from"node:process";var Xq=/^[a-zA-Z0-9._-]+$/;function qw(){return df.join(Oq(),".stacks","rpx","registry.d")}function T1($){return typeof $==="string"&&$.length>0&&$.length<=128&&Xq.test($)}function lf($,w){if(!T1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return df.join($,`${w}.json`)}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"&&T1(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 c$.mkdir($,{recursive:!0})}async function GF($,w=qw(),A){if(!TF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await _q(w);let J=lf(w,$.id),U=`${J}.tmp.${gf.pid}.${Date.now()}`,Y=JSON.stringify($,null,2);try{await c$.writeFile(U,Y,{encoding:"utf8",mode:420}),await c$.rename(U,J),z("registry",`wrote entry ${$.id} → ${J}`,A)}catch(f){throw await c$.unlink(U).catch(()=>{}),f}}async function qF($,w=qw(),A){let J=lf(w,$);try{await c$.unlink(J),z("registry",`removed entry ${$}`,A)}catch(U){if(U.code!=="ENOENT")throw U}}async function tf($,w=qw(),A){let J=lf(w,$);try{let U=await c$.readFile(J,"utf8"),Y=JSON.parse(U);if(!TF(Y))return z("registry",`entry ${$} failed validation, removing`,A),await c$.unlink(J).catch(()=>{}),null;return Y}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await c$.unlink(J).catch(()=>{}),null;throw U}}async function NF($=qw(),w){let A;try{A=await c$.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(!T1(Y))continue;let f=await tf(Y,$,w);if(f)J.push(f)}return J}p0();import{execSync as bq}from"node:child_process";import*as Mw from"node:http";import*as SF from"node:http2";import*as VF from"node:net";import*as o from"node:process";var CU=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,G0={bold:CU(1,22),dim:CU(2,22),green:CU(32,39),cyan:CU(36,39)};Q8();Df();p0();m1();U$();import*as RF from"node:fs";import*as KF from"node:path";import*as q0 from"node:process";function Dq($){let w=$.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return w.length>0?w:"rpx"}async function pf($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,J=new Set,U=$.proxies.map((j)=>{let F=j.id??Dq(j.to);if(!n1(F))throw Error(`invalid registry id "${F}" derived from to="${j.to}"`);if(J.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return J.add(F),{...j,id:F}}),Y=new Date().toISOString();for(let j of U)await ph({id:j.id,from:j.from,to:j.to,pid:$.persistent?void 0:q0.pid,cwd:q0.cwd(),createdAt:Y,cleanUrls:j.cleanUrls,changeOrigin:j.changeOrigin,pathRewrites:j.pathRewrites},A,w);let f=await sh({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let j of U)R.success(`https://${j.to} → ${j.from}`);if(R.info(`(via rpx daemon pid=${f.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,Z=A??Aw(),E=U.map((j)=>j.id),B=async()=>{if(W)return;W=!0;for(let j of E)await Xf(j,A,w).catch((F)=>{z("runner",`removeEntry(${j}) failed: ${F}`,w)})},h=(j)=>{z("runner",`received ${j}, unregistering ${E.length} entries`,w),B().finally(()=>q0.exit(0))};q0.once("SIGINT",h),q0.once("SIGTERM",h),q0.once("exit",()=>{if(W)return;for(let j of E)try{RF.unlinkSync(KF.join(Z,`${j}.json`))}catch{}}),await new Promise(()=>{})}U$();import{exec as kq}from"node:child_process";import Nw from"node:fs";import IF from"node:os";import af from"node:path";import*as t1 from"node:process";import{promisify as Qq}from"node:util";var yU=Qq(kq);function MF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var Y0=t1.platform==="win32"?af.join(t1.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",rf=!1;async function LU($){if(t1.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Bw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:J}=await yU(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return rf=!0,J}if(rf)try{let{stdout:J}=await yU(`sudo -n sh -c '${A}'`);return J}catch(J){z("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:J}=await yU(`sudo -n sh -c '${A}'`);return rf=!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 p1($,w){let A=$.filter((U)=>!MF(U)),J=$.filter((U)=>MF(U));if(J.length>0)z("hosts",`Skipping /etc/hosts for loopback dev names: ${J.join(", ")}`,w);if(A.length===0)return;z("hosts",`Adding hosts: ${A.join(", ")}`,w),z("hosts",`Using hosts file at: ${Y0}`,w);try{let U;try{U=await Nw.promises.readFile(Y0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{U=await LU(`cat "${Y0}"`)}catch(Z){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${Z}`,w),Error(`Cannot read hosts file: ${Z}`)}}let Y=A.filter((Z)=>{let E=`127.0.0.1 ${Z}`,B=`::1 ${Z}`;return!U.includes(E)&&!U.includes(B)});if(Y.length===0){z("hosts","All hosts already exist in hosts file",w);return}let f=Y.map((Z)=>`
|
|
243
243
|
# Added by rpx
|
|
244
|
-
127.0.0.1 ${
|
|
245
|
-
::1 ${
|
|
246
|
-
`),
|
|
244
|
+
127.0.0.1 ${Z}
|
|
245
|
+
::1 ${Z}`).join(`
|
|
246
|
+
`),W=af.join(IF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Nw.promises.writeFile(W,U+f,"utf8"),await LU(`cat "${W}" | tee "${Y0}" > /dev/null`),console.log(` Hosts updated: ${Y.join(", ")}`)}catch(Z){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),Y.forEach((E)=>{console.log(` 127.0.0.1 ${E}`),console.log(` ::1 ${E}`)}),console.log(` Or run: sudo nano ${Y0}`)}finally{try{await Nw.promises.unlink(W)}catch{}}}catch(U){z("hosts",`Failed to manage hosts file: ${U.message}`,w)}}async function CF($,w){z("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await Nw.promises.readFile(Y0,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await LU(`cat "${Y0}"`)}catch(Z){throw z("hosts",`sudo read also failed: ${Z}`,w),Error(`Cannot read hosts file: ${Z}`)}}let J=A.split(`
|
|
247
247
|
`),U=!1,Y=J.filter((Z)=>{if($.some((B)=>Z.includes(` ${B}`)&&(Z.includes("127.0.0.1")||Z.includes("::1"))))return U=!0,!1;if(Z.trim()==="# Added by rpx")return U=!0,!1;return!0});if(!U){z("hosts","No matching hosts found to remove",w);return}while(Y[Y.length-1]?.trim()==="")Y.pop();let f=`${Y.join(`
|
|
248
248
|
`)}
|
|
249
|
-
`,W=af.join(MF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Nw.promises.writeFile(W,f,"utf8"),await LU(`cat "${W}" | tee "${Y0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(Z){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Nw.promises.unlink(W)}catch(Z){z("hosts",`Failed to remove temporary file: ${Z}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function r1($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Nw.promises.readFile(Y0,"utf-8")}catch(J){z("hosts",`Error reading hosts file: ${J}`,w);try{let U=Bw(),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 yU(Y);A=f}catch(U){return z("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)})}hU();U$();import*as SU from"node:net";function Rw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let U=SU.createServer(),Y=setTimeout(()=>{z("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")z("port",`Port ${$} is in use`,A),J(!0);else z("port",`Error checking port ${$}: ${f.message}`,A),J(!0)}),U.once("listening",()=>{clearTimeout(Y),z("port",`Port ${$} is available`,A),U.close(),J(!1)});try{U.listen($,w)}catch(f){clearTimeout(Y),z("port",`Exception checking port ${$}: ${f}`,A),J(!0)}})}async function Qq($,w,A,J=50){z("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let U=$,Y=0;while(Y<J){if(Y++,!await Rw(U,w,A))return z("port",`Found available port: ${U} after ${Y} attempts`,A),U;z("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 CF($,w,A=5000,J){return z("port",`Testing connection to ${w}:${$}`,J),new Promise((U)=>{let Y=SU.connect({host:w,port:$,timeout:A});Y.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,J),Y.end(),U(!0)}),Y.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,J),Y.destroy(),U(!1)}),Y.once("error",(f)=>{z("port",`Failed to connect to ${w}:${$}: ${f.message}`,J),Y.destroy(),U(!1)})})}class VU{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 Rw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await CF($,this.hostname,3000,this.verbose))return z("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await Qq($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await CF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){z("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var $y=new VU;p0();U$();import{spawn as xq}from"node:child_process";import*as Kw from"node:process";class OU{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Kw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${J0(w.env)}`,A);let f=xq(J,U,{cwd:Y,env:{...Kw.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",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),Z(E),Kw.emit("SIGINT")}),f.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),Z(Error(`Process ${$} exited with code ${E}`)),Kw.emit("SIGINT")}),A)f.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),f.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),Z(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((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 Yy=new OU;FU();U$();var _U=new OU,bq="0.12.0",iq=new VU("0.0.0.0"),a1=new Set,sf=!1,XU=null,of=null;async function DU($){if(sf)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),of||Promise.resolve();sf=!0,z("cleanup","Starting cleanup process",$?.verbose),of=new Promise((w)=>{XU=w});try{await _U.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],A=Array.from(a1).map((J)=>new Promise((U)=>{J.close(()=>{z("cleanup","Server closed successfully",$?.verbose),U()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)R.info("Cleaning up hosts file entries..."),w.push(IF(J,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((U)=>{z("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let J=$.domains.map(async(U)=>{try{await gh(U,$?.verbose),z("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(Y){z("cleanup",`Failed to remove certificates for ${U}: ${Y}`,$?.verbose),R.warn(`Failed to clean up certificates for ${U}:`,Y)}});w.push(...J)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(XU)XU();XU=null,sf=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(o.env.NODE_ENV!=="test"&&o.env.BUN_ENV!=="test"&&!w)o.exit(0)}return of}var ef=!1;function $Z($){if(ef){z("signal",`Received second ${$} signal, forcing exit`,!0),o.exit(1);return}ef=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),DU().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),o.exit(1)}).finally(()=>{ef=!1})}o.once("SIGINT",()=>$Z("SIGINT"));o.once("SIGTERM",()=>$Z("SIGTERM"));o.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),R.error("Uncaught exception:",$),$Z("uncaughtException")});async function s1($,w,A,J=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let U=15000,Y=Date.now();if(o.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let f=()=>new Promise((W,Z)=>{let E=SF.connect({host:$,port:w,timeout:3000});E.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),E.end(),W()}),E.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),E.destroy(),Z(Error("Connection timed out"))}),E.once("error",(B)=>{z("connection",`Failed to connect to ${$}:${w}: ${B}`,A),E.destroy(),Z(B)})});try{await f()}catch(W){if(Date.now()-Y>U){z("connection",`Connection test timed out after ${U}ms, but continuing anyway`,A),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&J>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),s1($,w,A,J-1);if(J>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((E,B)=>{let h=Mw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(j)=>{z("connection",`Received HTTP response with status: ${j.statusCode}`,A),E()});h.on("error",(j)=>B(j)),h.on("timeout",()=>{h.destroy(),B(Error("HTTP request timed out"))}),h.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(E){return z("connection",`HTTP request to ${$}:${w} failed: ${E}`,A),z("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),s1($,w,A,J-1)}let Z=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${W.message}`;z("connection",`${Z}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),R.warn(Z),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 VF($){z("server",`Starting server with options: ${J0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),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")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await r1(U,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await p1(U,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),o.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 z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(f){R.error("Failed to check hosts file:",f.message)}}try{await s1(w.hostname,J,$.verbose)}catch(f){z("server",`Connection test failed: ${f}`,$.verbose),R.error(f.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 Y=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=u1({...$,to:A.hostname});if(Y=await v0({...$,to:A.hostname,https:$.https}),!Y){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await j1({...$,from:w.toString(),to:A.hostname,https:$.https}),Y=await v0({...$,to:A.hostname,https:$.https}),!Y)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(f){throw z("server",`SSL setup failed: ${f}`,$.verbose),f}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await uq({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:Y})}async function cq($,w,A,J,U,Y,f,W,Z,E,B){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${E}`,Z);function h(H){let G={};for(let[q,N]of Object.entries(H))if(!q.startsWith(":"))G[q]=N;return G}let j=(H,G)=>{z("request",`Incoming request: ${H.method} ${H.url}`,Z);let q=H.url||"/",N=H.method||"GET";if(H instanceof LF.Http2ServerRequest){let S=H.headers;N=S[":method"]||N,q=S[":path"]||q}if(E){if(!q.match(/\.[a-z0-9]+$/i))if(q.endsWith("/"))q=`${q}index.html`;else q=`${q}.html`}let K=h(H.headers);if(B)K.host=`${Y.hostname}:${A}`,z("request",`Changed origin: setting host header to ${K.host}`,Z);let C={hostname:Y.hostname,port:A,path:q,method:N,headers:K};z("request",`Proxy request options: ${J0(C)}`,Z);let y=Mw.request(C,(S)=>{if(z("response",`Proxy response received with status ${S.statusCode}`,Z),E&&S.statusCode===404){let f$=[];if(q.endsWith(".html"))f$.push(q.slice(0,-5));else if(!q.match(/\.[a-z0-9]+$/i))f$.push(`${q}.html`);if(!q.endsWith("/"))f$.push(`${q}/index.html`);if(f$.length>0){z("cleanUrls",`Trying alternative paths: ${f$.join(", ")}`,Z);let H0=(o1)=>{if(o1.length===0){G.writeHead(S.statusCode||404,S.headers),S.pipe(G);return}let wZ=o1[0],QF={...C,path:wZ},AZ=Mw.request(QF,(e1)=>{if(e1.statusCode===200)z("cleanUrls",`Found matching path: ${wZ}`,Z),G.writeHead(e1.statusCode,e1.headers),e1.pipe(G);else H0(o1.slice(1))});AZ.on("error",()=>H0(o1.slice(1))),AZ.end()};H0(f$);return}}let L={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};G.writeHead(S.statusCode||500,L),S.pipe(G)});y.on("error",(S)=>{z("request",`Proxy request failed: ${S}`,Z),R.error("Proxy request failed:",S),G.writeHead(502),G.end(`Proxy Error: ${S.message}`)}),H.pipe(y)};if(z("server",`Creating server with SSL config: ${!!f}`,Z),f)return new Promise((H,G)=>{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 K=new URL(N.url);z("request",`Bun.serve received: ${N.method} ${K.pathname}`,Z);let C=`http://${Y.host}`,y=new URL(K.pathname+K.search,C);try{let S=new Headers(N.headers);if(S.set("host",Y.host),B)S.set("origin",C);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",w);let L=await fetch(y.toString(),{method:N.method,headers:S,body:N.body,redirect:"manual"}),f$=new Headers(L.headers);if(E&&K.pathname.endsWith(".html")){let H0=K.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H0}})}return new Response(L.body,{status:L.status,statusText:L.statusText,headers:f$})}catch(S){return z("request",`Proxy error: ${S}`,Z),new Response(`Proxy Error: ${S}`,{status:502})}},error(N){return z("server",`Bun.serve error: ${N}`,Z),new Response(`Server Error: ${N.message}`,{status:500})}});a1.add(q),yF({from:$,to:w,vitePluginUsage:W,listenPort:J,ssl:!0,cleanUrls:E,verbose:Z}),H()}catch(q){G(q)}});let F=Mw.createServer(j);function T(H){return a1.add(H),new Promise((G,q)=>{H.listen(J,U,()=>{z("server",`Server listening on port ${J}`,Z),yF({from:$,to:w,vitePluginUsage:W,listenPort:J,ssl:!!f,cleanUrls:E,verbose:Z}),G()}),H.on("error",(N)=>{z("server",`Server error: ${N}`,Z),q(N)})})}return T(F)}async function uq($){z("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:E,cleanUrls:B}=$,h=80,j=443,F="0.0.0.0",T=$.portManager||iq;try{if(A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await r1([A],f))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await p1([A],f),R.success(`Added ${A} to your hosts file.`)}catch(K){R.error(`Failed to add ${A} to your hosts file: ${K}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(o.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await r1([A],f))[0]){z("hosts",`${A} not found in hosts file, adding...`,f);try{await p1([A],f)}catch(K){z("hosts",`Failed to add ${A} to hosts file: ${K}`,f)}}}if(Y&&!T.usedPorts.has(h)){if(!await Rw(h,F,f))z("setup","Starting HTTP redirect server",f),OF(f),T.usedPorts.add(h);else if(z("setup","Port 80 is in use, skipping HTTP redirect",f),f)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let H=Y?j:h,G=await Rw(H,F,f),q;if(G){if(z("setup",`Port ${H} is already in use`,f),f)R.warn(`Port ${H} is already in use. This may be another instance of rpx or another service.`);if(H===443){if(q=await T.getNextAvailablePort(3443,!0),z("setup",`Using port ${q} instead of ${H}`,f),f)R.info(`Using port ${q} instead. Access your site at https://${A}:${q}`)}else if(q=await T.getNextAvailablePort(H+1000,!0),z("setup",`Using port ${q} instead of ${H}`,f),f)R.info(`Using port ${q} instead. Access your site at http://${A}:${q}`)}else q=H,T.usedPorts.add(q),z("setup",`Using standard ${H===443?"HTTPS":"HTTP"} port ${H} for ${A}`,f);await cq(w,A,J,q,F,U,Y,Z,f,B,E)}catch(H){z("setup",`Setup failed: ${H}`,f),R.error(`Failed to setup reverse proxy: ${H.message}`),DU({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:f,vitePluginUsage:Z})}}function OF($){z("redirect","Starting HTTP redirect server",$);let w=Mw.createServer((A,J)=>{let U=A.headers.host||"";z("redirect",`Redirecting request from ${U}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${U}${A.url}`}),J.end()}).listen(80);a1.add(w),z("redirect","HTTP redirect server started",$)}function XF($){let w={...k8,...$};if(z("proxy",`Starting proxy with options: ${J0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}pf({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((Z)=>{R.error(`Failed to register with rpx daemon: ${Z.message}`),o.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",U=o.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)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(U)Promise.resolve().then(() => (z1(),KU)).then(({setupDevelopmentDns:Z})=>{Z({domains:[A],verbose:w.verbose}).then((E)=>{if(E)Promise.resolve().then(()=>{if(w.verbose)if(f.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 z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((Z)=>{z("dns",`Failed to start DNS server: ${Z}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:u1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${J0(W)}`,w.verbose),VF(W).catch((Z)=>{z("proxy",`Failed to start proxy: ${Z}`,w.verbose),R.error(`Failed to start proxy: ${Z.message}`),DU({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 vq($){return $?.verbose||!1}async function _F($){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=vq(w);if(z("config",`Starting with config: ${J0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),w.viaDaemon){let T="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({id:H.id,from:H.from,to:H.to,cleanUrls:H.cleanUrls??w.cleanUrls,changeOrigin:H.changeOrigin??w.changeOrigin,pathRewrites:H.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await pf({proxies:T,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let F of w.proxies)if(F.start){let T=`${F.from}-${F.to}`;try{z("watch",`Starting command for ${T} with command: ${F.start.command}`,A),R.info(`Starting command for ${T}...`),await _U.startProcess(T,F.start,A);let H=new URL(F.from.startsWith("http")?F.from:`http://${F.from}`),G=H.hostname||"localhost",q=Number(H.port)||80;try{await s1(G,q,A),z("watch",`Dev server is ready at ${G}:${q}`,A)}catch(N){z("watch",`Connection check failed, but continuing with proxy setup: ${N}`,A),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw z("watch",`Failed to start command for ${T}: ${H}`,A),Error(`Failed to start command for ${T}: ${H}`)}}else z("watch",`No start command for proxy ${F.from} -> ${F.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let F=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await _U.startProcess(F,w.start,A);let T=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),H=T.hostname||"localhost",G=Number(T.port)||80;try{await s1(H,G,A),z("watch",`Dev server is ready at ${H}:${G}`,A)}catch(q){z("watch",`Connection check failed, but continuing with proxy setup: ${q}`,A),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw z("watch",`Failed to run start command: ${T}`,A),Error(`Failed to run start command: ${T}`)}}else z("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(o.platform!=="win32"&&(w.https||w.cleanup?.hosts!==!1)){if(!Bw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),Pq("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let F=await v0(w);if(!F){if(z("ssl",`No valid or trusted certificates found for ${J}, generating new ones`,w.verbose),await j1(w),F=await v0(w),!F)throw Error(`Failed to load SSL certificates after generation for ${J}`)}else z("ssl",`Using existing and trusted certificates for ${J}`,w.verbose);w._cachedSSLConfig=F}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((F)=>({...F,https:w.https,cleanup:w.cleanup,cleanUrls:F.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:F.changeOrigin??w.changeOrigin,verbose: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((F)=>F.to||"rpx.localhost"),f=w._cachedSSLConfig,W=Y.filter((F)=>F&&!F.includes("localhost")&&!F.includes("127.0.0.1")),Z=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],B=[...new Set(W.map((F)=>F.split(".").pop()?.toLowerCase()))],h=B.filter((F)=>!!F&&Z.includes(F));if(h.length>0&&A)R.warn(`The following TLDs may not work reliably for local development: ${h.map((F)=>`.${F}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(o.platform==="darwin"&&W.length>0){let{setupDevelopmentDns:F}=await Promise.resolve().then(() => (z1(),KU));if(await F({domains:W,verbose:A})){if(A)if(B.every((G)=>!!G&&E.includes(G)))R.success(`DNS server started for ${B.map((G)=>`.${G}`).join(", ")} domains`);else R.success(`DNS server started for ${B.map((G)=>`.${G}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let j=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:F}=await Promise.resolve().then(() => (z1(),KU));await F({verbose:w.verbose})}catch(F){z("cleanup",`Error stopping DNS server: ${F}`,w.verbose)}try{await _U.stopAll(w.verbose)}catch(F){z("cleanup",`Error stopping processes: ${F}`,w.verbose)}await DU({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(o.on("SIGINT",j),o.on("SIGTERM",j),o.on("uncaughtException",(F)=>{z("process",`Uncaught exception: ${F}`,!0),console.error("Uncaught exception:",F),j()}),f&&U.length>1){z("proxies",`Creating shared HTTPS server for ${U.length} domains`,A);let F=new Map;for(let q of U){let N=q.to||"rpx.localhost",K=new URL(q.from?.startsWith("http")?q.from:`http://${q.from}`);if(F.set(N,{sourceHost:K.host,cleanUrls:q.cleanUrls||!1,changeOrigin:q.changeOrigin||!1,pathRewrites:q.pathRewrites}),z("proxies",`Route: ${N} → ${K.host}`,A),!N.includes("localhost")&&!N.includes("127.0.0.1"))try{if(!(await r1([N],A))[0])await p1([N],A)}catch{z("hosts",`Could not add hosts entry for ${N}`,A)}}if(!await Rw(80,"0.0.0.0",A))OF(A);let H=443;if(await Rw(H,"0.0.0.0",A)){if(z("proxies",`Port ${H} is already in use, cannot start shared proxy`,A),A)R.warn(`Port ${H} is in use. Shared HTTPS proxy cannot start.`);return}try{let q=Bun.serve({port:H,hostname:"0.0.0.0",tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},fetch:v1((N)=>F.get(N),A),error(N){return z("server",`Shared proxy server error: ${N}`,A),new Response(`Server Error: ${N.message}`,{status:500})}});a1.add(q),z("proxies",`Shared HTTPS proxy listening on port ${H} for ${F.size} domains`,A)}catch(q){z("proxies",`Failed to start shared proxy: ${q}`,A),console.error("Failed to start shared HTTPS proxy:",q),j()}}else for(let F of U)try{let T=F.to||"rpx.localhost";z("proxy",`Starting proxy for ${T} with SSL config: ${!!f}`,F.verbose),await VF({from:F.from||"localhost:5173",to:T,cleanUrls:F.cleanUrls||!1,https:F.https||!1,cleanup:F.cleanup||!1,vitePluginUsage:F.vitePluginUsage||!1,verbose:F.verbose||!1,_cachedSSLConfig:f,changeOrigin:F.changeOrigin||!1})}catch(T){z("proxies",`Failed to start proxy for ${F.to}: ${T}`,F.verbose),console.error(`Failed to start proxy for ${F.to}:`,T),j()}}function yF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${G0.green(G0.bold("rpx"))} ${G0.green(`v${bq}`)}`),console.log(` ${G0.green("➜")} ${G0.dim($?.from??"")} ${G0.dim("➜")} ${G0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${G0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${G0.green("➜")} Clean URLs enabled`)}qf();var Iy=new Ew("rpx",{showTags:!1});function DF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}var v$=new vU("rpx"),kF="0.12.0";v$.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 _F(Pw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(J){console.error("Failed to parse start-env JSON:",J),r$.exit(1)}w.start=A}return XF(w)});v$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=DF(Pw)?Pw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):Pw.to===$?Pw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),r$.exit(1);try{await IU.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(J){console.error(`Failed to start dev server for ${$}:`,J),r$.exit(1)}});v$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await IU.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),r$.exit(1)}});v$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await IU.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),r$.exit(1)}});v$.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 hF({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,r$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),r$.exit(1)}});v$.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 jF({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)":""}`)});v$.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 Hw(w),J=await MU(w),U=$.registryDir,Y=await NF(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:Tw(w),rpxDir:w,registryDir:U??qw(),entries:Y},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Tw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Tw(w)}`);if(console.log(`registry: ${U??qw()}`),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})`)}});v$.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"),r$.exit(1);if(!T1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),r$.exit(1);try{await GF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),r$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await FF({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`"),r$.exit(1)}});v$.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(!T1($))console.error(`invalid id: ${JSON.stringify($)}`),r$.exit(1);let A=await tf($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await qF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});v$.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 MU(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await zF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});v$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(kF)});v$.version(kF);v$.help();v$.run();
|
|
249
|
+
`,W=af.join(IF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await Nw.promises.writeFile(W,f,"utf8"),await LU(`cat "${W}" | tee "${Y0}" > /dev/null`),z("hosts","Hosts removed successfully",w)}catch(Z){z("hosts","Could not clean up hosts file automatically",w)}finally{try{await Nw.promises.unlink(W)}catch(Z){z("hosts",`Failed to remove temporary file: ${Z}`,w)}}}catch(A){z("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function r1($,w){z("hosts",`Checking hosts: ${$}`,w);let A;try{A=await Nw.promises.readFile(Y0,"utf-8")}catch(J){z("hosts",`Error reading hosts file: ${J}`,w);try{let U=Bw(),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 yU(Y);A=f}catch(U){return z("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)})}hU();U$();import*as SU from"node:net";function Rw($,w,A){return z("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((J)=>{let U=SU.createServer(),Y=setTimeout(()=>{z("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")z("port",`Port ${$} is in use`,A),J(!0);else z("port",`Error checking port ${$}: ${f.message}`,A),J(!0)}),U.once("listening",()=>{clearTimeout(Y),z("port",`Port ${$} is available`,A),U.close(),J(!1)});try{U.listen($,w)}catch(f){clearTimeout(Y),z("port",`Exception checking port ${$}: ${f}`,A),J(!0)}})}async function xq($,w,A,J=50){z("port",`Finding available port starting from ${$} (max attempts: ${J})`,A);let U=$,Y=0;while(Y<J){if(Y++,!await Rw(U,w,A))return z("port",`Found available port: ${U} after ${Y} attempts`,A),U;z("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 yF($,w,A=5000,J){return z("port",`Testing connection to ${w}:${$}`,J),new Promise((U)=>{let Y=SU.connect({host:w,port:$,timeout:A});Y.once("connect",()=>{z("port",`Successfully connected to ${w}:${$}`,J),Y.end(),U(!0)}),Y.once("timeout",()=>{z("port",`Connection to ${w}:${$} timed out`,J),Y.destroy(),U(!1)}),Y.once("error",(f)=>{z("port",`Failed to connect to ${w}:${$}: ${f.message}`,J),Y.destroy(),U(!1)})})}class VU{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 Rw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await yF($,this.hostname,3000,this.verbose))return z("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await xq($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await yF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){z("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var Uy=new VU;p0();U$();import{spawn as Pq}from"node:child_process";import*as Kw from"node:process";class OU{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[J,...U]=w.command.split(" "),Y=w.cwd||Kw.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${J} ${U.join(" ")}`,A),z("start",` Working directory: ${Y}`,A),z("start",` Environment variables: ${J0(w.env)}`,A);let f=Pq(J,U,{cwd:Y,env:{...Kw.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",(E)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${E}`,A),this.processes.delete($),Z(E),Kw.emit("SIGINT")}),f.on("exit",(E)=>{if(!this.isShuttingDown&&E!==null&&E!==0)z("start",`Process ${$} exited with code ${E}`,A),this.processes.delete($),Z(Error(`Process ${$} exited with code ${E}`)),Kw.emit("SIGINT")}),A)f.stdout?.on("data",(E)=>{z("process",`[${$}] ${E.toString().trim()}`,!0)}),f.stderr?.on("data",(E)=>{z("process",`[${$}] ERR: ${E.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&f.killed)this.processes.delete($),Z(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((J)=>{if(!A.process){J();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),J()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){z("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),J()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((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 Ey=new OU;FU();U$();var _U=new OU,iq="0.12.0",cq=new VU("0.0.0.0"),a1=new Set,sf=!1,XU=null,of=null;async function DU($){if(sf)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),of||Promise.resolve();sf=!0,z("cleanup","Starting cleanup process",$?.verbose),of=new Promise((w)=>{XU=w});try{await _U.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],A=Array.from(a1).map((J)=>new Promise((U)=>{J.close(()=>{z("cleanup","Server closed successfully",$?.verbose),U()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let J=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(J)}`,$?.verbose),J.length>0)R.info("Cleaning up hosts file entries..."),w.push(CF(J,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${J.join(", ")}`,$?.verbose)}).catch((U)=>{z("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${J.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let J=$.domains.map(async(U)=>{try{await gh(U,$?.verbose),z("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(Y){z("cleanup",`Failed to remove certificates for ${U}: ${Y}`,$?.verbose),R.warn(`Failed to clean up certificates for ${U}:`,Y)}});w.push(...J)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(XU)XU();XU=null,sf=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(o.env.NODE_ENV!=="test"&&o.env.BUN_ENV!=="test"&&!w)o.exit(0)}return of}var ef=!1;function $Z($){if(ef){z("signal",`Received second ${$} signal, forcing exit`,!0),o.exit(1);return}ef=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),DU().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),o.exit(1)}).finally(()=>{ef=!1})}o.once("SIGINT",()=>$Z("SIGINT"));o.once("SIGTERM",()=>$Z("SIGTERM"));o.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),R.error("Uncaught exception:",$),$Z("uncaughtException")});async function s1($,w,A,J=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${J})`,A);let U=15000,Y=Date.now();if(o.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let f=()=>new Promise((W,Z)=>{let E=VF.connect({host:$,port:w,timeout:3000});E.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),E.end(),W()}),E.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),E.destroy(),Z(Error("Connection timed out"))}),E.once("error",(B)=>{z("connection",`Failed to connect to ${$}:${w}: ${B}`,A),E.destroy(),Z(B)})});try{await f()}catch(W){if(Date.now()-Y>U){z("connection",`Connection test timed out after ${U}ms, but continuing anyway`,A),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&J>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${J} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),s1($,w,A,J-1);if(J>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((E,B)=>{let h=Mw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(j)=>{z("connection",`Received HTTP response with status: ${j.statusCode}`,A),E()});h.on("error",(j)=>B(j)),h.on("timeout",()=>{h.destroy(),B(Error("HTTP request timed out"))}),h.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(E){return z("connection",`HTTP request to ${$}:${w} failed: ${E}`,A),z("connection",`Retrying socket connection in 2 seconds... (${J} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),s1($,w,A,J-1)}let Z=`Failed to connect to ${$}:${w} after ${5-J} attempts: ${W.message}`;z("connection",`${Z}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),R.warn(Z),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 OF($){z("server",`Starting server with options: ${J0($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),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")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await r1(U,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await p1(U,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),o.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 z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(f){R.error("Failed to check hosts file:",f.message)}}try{await s1(w.hostname,J,$.verbose)}catch(f){z("server",`Connection test failed: ${f}`,$.verbose),R.error(f.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 Y=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=u1({...$,to:A.hostname});if(Y=await v0({...$,to:A.hostname,https:$.https}),!Y){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await j1({...$,from:w.toString(),to:A.hostname,https:$.https}),Y=await v0({...$,to:A.hostname,https:$.https}),!Y)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(f){throw z("server",`SSL setup failed: ${f}`,$.verbose),f}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await vq({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:J,sourceUrl:{hostname:w.hostname,host:w.host},ssl:Y})}async function uq($,w,A,J,U,Y,f,W,Z,E,B){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${E}`,Z);function h(H){let G={};for(let[q,N]of Object.entries(H))if(!q.startsWith(":"))G[q]=N;return G}let j=(H,G)=>{z("request",`Incoming request: ${H.method} ${H.url}`,Z);let q=H.url||"/",N=H.method||"GET";if(H instanceof SF.Http2ServerRequest){let S=H.headers;N=S[":method"]||N,q=S[":path"]||q}if(E){if(!q.match(/\.[a-z0-9]+$/i))if(q.endsWith("/"))q=`${q}index.html`;else q=`${q}.html`}let K=h(H.headers);if(B)K.host=`${Y.hostname}:${A}`,z("request",`Changed origin: setting host header to ${K.host}`,Z);let C={hostname:Y.hostname,port:A,path:q,method:N,headers:K};z("request",`Proxy request options: ${J0(C)}`,Z);let y=Mw.request(C,(S)=>{if(z("response",`Proxy response received with status ${S.statusCode}`,Z),E&&S.statusCode===404){let f$=[];if(q.endsWith(".html"))f$.push(q.slice(0,-5));else if(!q.match(/\.[a-z0-9]+$/i))f$.push(`${q}.html`);if(!q.endsWith("/"))f$.push(`${q}/index.html`);if(f$.length>0){z("cleanUrls",`Trying alternative paths: ${f$.join(", ")}`,Z);let H0=(o1)=>{if(o1.length===0){G.writeHead(S.statusCode||404,S.headers),S.pipe(G);return}let wZ=o1[0],xF={...C,path:wZ},AZ=Mw.request(xF,(e1)=>{if(e1.statusCode===200)z("cleanUrls",`Found matching path: ${wZ}`,Z),G.writeHead(e1.statusCode,e1.headers),e1.pipe(G);else H0(o1.slice(1))});AZ.on("error",()=>H0(o1.slice(1))),AZ.end()};H0(f$);return}}let L={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};G.writeHead(S.statusCode||500,L),S.pipe(G)});y.on("error",(S)=>{z("request",`Proxy request failed: ${S}`,Z),R.error("Proxy request failed:",S),G.writeHead(502),G.end(`Proxy Error: ${S.message}`)}),H.pipe(y)};if(z("server",`Creating server with SSL config: ${!!f}`,Z),f)return new Promise((H,G)=>{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 K=new URL(N.url);z("request",`Bun.serve received: ${N.method} ${K.pathname}`,Z);let C=`http://${Y.host}`,y=new URL(K.pathname+K.search,C);try{let S=new Headers(N.headers);if(S.set("host",Y.host),B)S.set("origin",C);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",w);let L=await fetch(y.toString(),{method:N.method,headers:S,body:N.body,redirect:"manual"}),f$=new Headers(L.headers);if(E&&K.pathname.endsWith(".html")){let H0=K.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H0}})}return new Response(L.body,{status:L.status,statusText:L.statusText,headers:f$})}catch(S){return z("request",`Proxy error: ${S}`,Z),new Response(`Proxy Error: ${S}`,{status:502})}},error(N){return z("server",`Bun.serve error: ${N}`,Z),new Response(`Server Error: ${N.message}`,{status:500})}});a1.add(q),LF({from:$,to:w,vitePluginUsage:W,listenPort:J,ssl:!0,cleanUrls:E,verbose:Z}),H()}catch(q){G(q)}});let F=Mw.createServer(j);function T(H){return a1.add(H),new Promise((G,q)=>{H.listen(J,U,()=>{z("server",`Server listening on port ${J}`,Z),LF({from:$,to:w,vitePluginUsage:W,listenPort:J,ssl:!!f,cleanUrls:E,verbose:Z}),G()}),H.on("error",(N)=>{z("server",`Server error: ${N}`,Z),q(N)})})}return T(F)}async function vq($){z("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:E,cleanUrls:B}=$,h=80,j=443,F="0.0.0.0",T=$.portManager||cq;try{if(A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await r1([A],f))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await p1([A],f),R.success(`Added ${A} to your hosts file.`)}catch(K){R.error(`Failed to add ${A} to your hosts file: ${K}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(o.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await r1([A],f))[0]){z("hosts",`${A} not found in hosts file, adding...`,f);try{await p1([A],f)}catch(K){z("hosts",`Failed to add ${A} to hosts file: ${K}`,f)}}}if(Y&&!T.usedPorts.has(h)){if(!await Rw(h,F,f))z("setup","Starting HTTP redirect server",f),XF(f),T.usedPorts.add(h);else if(z("setup","Port 80 is in use, skipping HTTP redirect",f),f)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let H=Y?j:h,G=await Rw(H,F,f),q;if(G){if(z("setup",`Port ${H} is already in use`,f),f)R.warn(`Port ${H} is already in use. This may be another instance of rpx or another service.`);if(H===443){if(q=await T.getNextAvailablePort(3443,!0),z("setup",`Using port ${q} instead of ${H}`,f),f)R.info(`Using port ${q} instead. Access your site at https://${A}:${q}`)}else if(q=await T.getNextAvailablePort(H+1000,!0),z("setup",`Using port ${q} instead of ${H}`,f),f)R.info(`Using port ${q} instead. Access your site at http://${A}:${q}`)}else q=H,T.usedPorts.add(q),z("setup",`Using standard ${H===443?"HTTPS":"HTTP"} port ${H} for ${A}`,f);await uq(w,A,J,q,F,U,Y,Z,f,B,E)}catch(H){z("setup",`Setup failed: ${H}`,f),R.error(`Failed to setup reverse proxy: ${H.message}`),DU({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:f,vitePluginUsage:Z})}}function XF($){z("redirect","Starting HTTP redirect server",$);let w=Mw.createServer((A,J)=>{let U=A.headers.host||"";z("redirect",`Redirecting request from ${U}${A.url} to HTTPS`,$),J.writeHead(301,{Location:`https://${U}${A.url}`}),J.end()}).listen(80);a1.add(w),z("redirect","HTTP redirect server started",$)}function _F($){let w={...k8,...$};if(z("proxy",`Starting proxy with options: ${J0(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}pf({proxies:[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((Z)=>{R.error(`Failed to register with rpx daemon: ${Z.message}`),o.exit(1)});return}let A=w.to||"",J=A.split(".").pop()?.toLowerCase()||"",U=o.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)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(U)Promise.resolve().then(() => (z1(),KU)).then(({setupDevelopmentDns:Z})=>{Z({domains:[A],verbose:w.verbose}).then((E)=>{if(E)Promise.resolve().then(()=>{if(w.verbose)if(f.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 z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((Z)=>{z("dns",`Failed to start DNS server: ${Z}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:u1(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${J0(W)}`,w.verbose),OF(W).catch((Z)=>{z("proxy",`Failed to start proxy: ${Z}`,w.verbose),R.error(`Failed to start proxy: ${Z.message}`),DU({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 nq($){return $?.verbose||!1}async function DF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=nq(w);if(z("config",`Starting with config: ${J0(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),w.viaDaemon){let T="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({id:H.id,from:H.from,to:H.to,cleanUrls:H.cleanUrls??w.cleanUrls,changeOrigin:H.changeOrigin??w.changeOrigin,pathRewrites:H.pathRewrites})):[{id:w.id,from:w.from,to:w.to,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await pf({proxies:T,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let F of w.proxies)if(F.start){let T=`${F.from}-${F.to}`;try{z("watch",`Starting command for ${T} with command: ${F.start.command}`,A),R.info(`Starting command for ${T}...`),await _U.startProcess(T,F.start,A);let H=new URL(F.from.startsWith("http")?F.from:`http://${F.from}`),G=H.hostname||"localhost",q=Number(H.port)||80;try{await s1(G,q,A),z("watch",`Dev server is ready at ${G}:${q}`,A)}catch(N){z("watch",`Connection check failed, but continuing with proxy setup: ${N}`,A),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw z("watch",`Failed to start command for ${T}: ${H}`,A),Error(`Failed to start command for ${T}: ${H}`)}}else z("watch",`No start command for proxy ${F.from} -> ${F.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let F=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await _U.startProcess(F,w.start,A);let T=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),H=T.hostname||"localhost",G=Number(T.port)||80;try{await s1(H,G,A),z("watch",`Dev server is ready at ${H}:${G}`,A)}catch(q){z("watch",`Connection check failed, but continuing with proxy setup: ${q}`,A),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(T){throw z("watch",`Failed to run start command: ${T}`,A),Error(`Failed to run start command: ${T}`)}}else z("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(o.platform!=="win32"&&(w.https||w.cleanup?.hosts!==!1)){if(!Bw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),bq("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let F=await v0(w);if(!F){if(z("ssl",`No valid or trusted certificates found for ${J}, generating new ones`,w.verbose),await j1(w),F=await v0(w),!F)throw Error(`Failed to load SSL certificates after generation for ${J}`)}else z("ssl",`Using existing and trusted certificates for ${J}`,w.verbose);w._cachedSSLConfig=F}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((F)=>({...F,https:w.https,cleanup:w.cleanup,cleanUrls:F.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:F.changeOrigin??w.changeOrigin,verbose: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((F)=>F.to||"rpx.localhost"),f=w._cachedSSLConfig,W=Y.filter((F)=>F&&!F.includes("localhost")&&!F.includes("127.0.0.1")),Z=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],B=[...new Set(W.map((F)=>F.split(".").pop()?.toLowerCase()))],h=B.filter((F)=>!!F&&Z.includes(F));if(h.length>0&&A)R.warn(`The following TLDs may not work reliably for local development: ${h.map((F)=>`.${F}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(o.platform==="darwin"&&W.length>0){let{setupDevelopmentDns:F}=await Promise.resolve().then(() => (z1(),KU));if(await F({domains:W,verbose:A})){if(A)if(B.every((G)=>!!G&&E.includes(G)))R.success(`DNS server started for ${B.map((G)=>`.${G}`).join(", ")} domains`);else R.success(`DNS server started for ${B.map((G)=>`.${G}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let j=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:F}=await Promise.resolve().then(() => (z1(),KU));await F({verbose:w.verbose})}catch(F){z("cleanup",`Error stopping DNS server: ${F}`,w.verbose)}try{await _U.stopAll(w.verbose)}catch(F){z("cleanup",`Error stopping processes: ${F}`,w.verbose)}await DU({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(o.on("SIGINT",j),o.on("SIGTERM",j),o.on("uncaughtException",(F)=>{z("process",`Uncaught exception: ${F}`,!0),console.error("Uncaught exception:",F),j()}),f&&U.length>1){z("proxies",`Creating shared HTTPS server for ${U.length} domains`,A);let F=new Map;for(let q of U){let N=q.to||"rpx.localhost",K=new URL(q.from?.startsWith("http")?q.from:`http://${q.from}`);if(F.set(N,{sourceHost:K.host,cleanUrls:q.cleanUrls||!1,changeOrigin:q.changeOrigin||!1,pathRewrites:q.pathRewrites}),z("proxies",`Route: ${N} → ${K.host}`,A),!N.includes("localhost")&&!N.includes("127.0.0.1"))try{if(!(await r1([N],A))[0])await p1([N],A)}catch{z("hosts",`Could not add hosts entry for ${N}`,A)}}if(!await Rw(80,"0.0.0.0",A))XF(A);let H=443;if(await Rw(H,"0.0.0.0",A)){if(z("proxies",`Port ${H} is already in use, cannot start shared proxy`,A),A)R.warn(`Port ${H} is in use. Shared HTTPS proxy cannot start.`);return}try{let q=Bun.serve({port:H,hostname:"0.0.0.0",tls:{key:f.key,cert:f.cert,ca:f.ca,requestCert:!1,rejectUnauthorized:!1},fetch:v1((N)=>F.get(N),A),error(N){return z("server",`Shared proxy server error: ${N}`,A),new Response(`Server Error: ${N.message}`,{status:500})}});a1.add(q),z("proxies",`Shared HTTPS proxy listening on port ${H} for ${F.size} domains`,A)}catch(q){z("proxies",`Failed to start shared proxy: ${q}`,A),console.error("Failed to start shared HTTPS proxy:",q),j()}}else for(let F of U)try{let T=F.to||"rpx.localhost";z("proxy",`Starting proxy for ${T} with SSL config: ${!!f}`,F.verbose),await OF({from:F.from||"localhost:5173",to:T,cleanUrls:F.cleanUrls||!1,https:F.https||!1,cleanup:F.cleanup||!1,vitePluginUsage:F.vitePluginUsage||!1,verbose:F.verbose||!1,_cachedSSLConfig:f,changeOrigin:F.changeOrigin||!1})}catch(T){z("proxies",`Failed to start proxy for ${F.to}: ${T}`,F.verbose),console.error(`Failed to start proxy for ${F.to}:`,T),j()}}function LF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${G0.green(G0.bold("rpx"))} ${G0.green(`v${iq}`)}`),console.log(` ${G0.green("➜")} ${G0.dim($?.from??"")} ${G0.dim("➜")} ${G0.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${G0.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${G0.green("➜")} Clean URLs enabled`)}qf();var Sy=new Ew("rpx",{showTags:!1});function kF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}u$.chdir(dq(mq(gq(import.meta.url)),".."));var n$=new vU("rpx"),QF="0.12.0";n$.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return DF(Pw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(J){console.error("Failed to parse start-env JSON:",J),u$.exit(1)}w.start=A}return _F(w)});n$.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=kF(Pw)?Pw.proxies.find((J)=>J.to===$||`${J.from}-${J.to}`===$):Pw.to===$?Pw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),u$.exit(1);try{await IU.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(J){console.error(`Failed to start dev server for ${$}:`,J),u$.exit(1)}});n$.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await IU.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),u$.exit(1)}});n$.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await IU.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),u$.exit(1)}});n$.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 hF({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,u$.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),u$.exit(1)}});n$.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 jF({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)":""}`)});n$.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 Hw(w),J=await MU(w),U=$.registryDir,Y=await NF(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:J,pid:A,pidFile:Tw(w),rpxDir:w,registryDir:U??qw(),entries:Y},null,2));return}if(!J){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Tw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Tw(w)}`);if(console.log(`registry: ${U??qw()}`),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})`)}});n$.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"),u$.exit(1);if(!T1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),u$.exit(1);try{await GF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),u$.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await FF({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`"),u$.exit(1)}});n$.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(!T1($))console.error(`invalid id: ${JSON.stringify($)}`),u$.exit(1);let A=await tf($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await qF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});n$.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 MU(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await zF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});n$.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(QF)});n$.version(QF);n$.help();n$.run();
|