@stacksjs/rpx 0.11.11 → 0.11.13

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.
@@ -1,21 +1,21 @@
1
- import{Aa as Eh,Ca as Rh,Da as Th,pa as W,ra as rr,sa as w,wa as Ah,xa as zf,za as zn}from"./chunk-zs1tyy8z.js";import cw from"node:dgram";import*as Yh from"node:fs/promises";import*as Ih from"node:path";import*as Qt from"node:process";import{spawn as vy}from"node:child_process";import*as Lt from"node:fs/promises";import{homedir as Jh}from"node:os";import*as It from"node:path";import*as D from"node:process";var M={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};import{execSync as Mi}from"node:child_process";import k from"node:fs/promises";import*as Mf from"node:os";import{homedir as Gn}from"node:os";import{join as Q}from"node:path";import*as Yt from"node:process";import{createRequire as zh}from"node:module";import Vn from"node:os";import pn from"node:path";import{existsSync as es,statSync as fs}from"fs";import{existsSync as Gh,mkdirSync as Jw,readdirSync as Nw,readFileSync as qh,writeFileSync as jw}from"fs";import{homedir as ui}from"os";import{dirname as Yw,resolve as Tt}from"path";import Vr from"process";import{existsSync as ss,statSync as ls}from"fs";import{existsSync as we,mkdirSync as Kh,readdirSync as xh,writeFileSync as kh}from"fs";import{homedir as ai}from"os";import{dirname as cs,resolve as ht}from"path";import ci from"process";import{join as Dh,relative as bh,resolve as hs}from"path";import Wr from"process";import{existsSync as Ps,mkdirSync as Kw,readdirSync as xw,writeFileSync as kw}from"fs";import{homedir as Pn}from"os";import{dirname as Vw,resolve as ct}from"path";import Di from"process";import{join as Vh,relative as ph,resolve as os}from"path";import Yr from"process";import{existsSync as vs,mkdirSync as Qw,readdirSync as t0,writeFileSync as i0}from"fs";import{dirname as n0,resolve as Ir}from"path";import me from"process";import{Buffer as ti}from"buffer";import{createCipheriv as Ph,createDecipheriv as vh,randomBytes as vn}from"crypto";import{closeSync as Xn,createReadStream as us,createWriteStream as Xh,existsSync as Qn,fsyncSync as as,openSync as $s,writeFileSync as Qh}from"fs";import{access as to,constants as ys,mkdir as io,readdir as $r,rename as ws,stat as $i,unlink as yr,writeFile as te}from"fs/promises";import{join as yi}from"path";import rt from"process";import{pipeline as ro}from"stream/promises";import{createGzip as ms}from"zlib";import wi from"process";import Gt from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as no,createDecipheriv as eo,randomBytes as ie}from"crypto";import{closeSync as re,createReadStream as ds,createWriteStream as fo,existsSync as wr,fsyncSync as As,openSync as Es,writeFileSync as so}from"fs";import{access as lo,constants as Ts,mkdir as co,readdir as mr,rename as gs,stat as mi,unlink as dr,writeFile as ne}from"fs/promises";import{isAbsolute as ho,join as di,resolve as oo}from"path";import N from"process";import{pipeline as uo}from"stream/promises";import{createGzip as Ss}from"zlib";import Ai from"process";import qt from"process";import Ar from"process";import{existsSync as Er}from"fs";import{resolve as ee}from"path";import{existsSync as ao}from"fs";import{existsSync as $o,readdirSync as yo}from"fs";import{extname as fe,resolve as Cs}from"path";import wo from"process";import{join as mo,relative as Ao,resolve as Rs}from"path";import Or from"process";import{Buffer as Mt}from"buffer";import{createCipheriv as Eo,createDecipheriv as To,randomBytes as se}from"crypto";import{closeSync as le,createReadStream as Bs,createWriteStream as go,existsSync as Tr,fsyncSync as Us,openSync as Fs,writeFileSync as So}from"fs";import{access as Co,constants as Js,mkdir as Ro,readdir as gr,rename as Ns,stat as Ei,unlink as Sr,writeFile as ce}from"fs/promises";import{isAbsolute as Bo,join as Ti,resolve as Uo}from"path";import j from"process";import{pipeline as Fo}from"stream/promises";import{createGzip as js}from"zlib";import gi from"process";import Kt from"process";import Cr from"process";import{existsSync as Rr}from"fs";import{resolve as he}from"path";import{existsSync as Jo}from"fs";import{exec as Pu}from"node:child_process";import xs from"node:fs";import vu from"node:os";import Ut from"node:path";import Yl from"node:process";import{promisify as Xu}from"node:util";import Bi from"node:crypto";import xt from"node:fs";import Ne from"node:path";import{execSync as ps}from"node:child_process";import br from"node:os";var Cw=zh(import.meta.url);class Xs{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!es(t))return!0;return fs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=es(r)?fs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Qs{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Hr=new Xs,je=new Qs,No=Object.defineProperty,jo=(t)=>t;function _o(t,i){this[t]=jo.bind(null,i)}var Wo=(t,i)=>{for(var r in i)No(t,r,{get:i[r],enumerable:!0,configurable:!0,set:_o.bind(i,r)})},Yo=(t,i)=>()=>(t&&(i=t(t=0)),i),tl={};Wo(tl,{withErrorRecovery:()=>nl,tryLoadConfig:()=>ru,loadConfigWithResult:()=>tu,loadConfig:()=>cl,isRetryableError:()=>Vo,isConfigNotFoundError:()=>bo,isBunfigError:()=>el,globalPerformanceMonitor:()=>Pi,globalCache:()=>Ci,getEnvOrDefault:()=>po,generateConfigTypes:()=>nu,defaultGeneratedDir:()=>ml,defaultConfigDir:()=>wl,deepMergeWithArrayStrategy:()=>Oe,deepMerge:()=>fl,createLibraryConfig:()=>eu,config:()=>iu,bunfigPlugin:()=>fu,applyEnvVarsToConfig:()=>xi,TypeGenerationError:()=>Ce,SchemaValidationError:()=>Vi,PluginError:()=>Be,PerformanceMonitor:()=>We,FileSystemError:()=>Se,ErrorFactory:()=>ri,EnvVarError:()=>qr,EnvProcessor:()=>pr,ConfigValidator:()=>He,ConfigValidationError:()=>Te,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>ge,ConfigLoader:()=>Le,ConfigLoadError:()=>bi,ConfigFileLoader:()=>Pr,ConfigCache:()=>_e,CacheUtils:()=>ol,BunfigError:()=>mt,BrowserConfigError:()=>Re,ArrayMergeStrategies:()=>$l});class _e{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!ss(t))return!0;return ls(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=ss(r)?ls(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class We{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Io(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function Oo(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Ho(t){return t.getStats().size*2}function Ye(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&z(i[0])&&"id"in i[0]&&i[0].id===3&&z(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(z(i)&&z(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(z(t)&&"arr"in t&&Array.isArray(t.arr)&&z(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&z(i[0])&&z(t[0])){let n=[...i];for(let e of t)if(z(e)&&"name"in e){if(!n.find((f)=>z(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(z(e)&&"path"in e){if(!n.find((f)=>z(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Lr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!z(i)||!z(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(z(e)&&z(r[n]))r[n]=Ye(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&z(e[0])&&z(r[n][0])){let f=[...e];for(let s of r[n])if(z(s)&&"name"in s){if(!f.find((c)=>z(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(z(s)&&"path"in s){if(!f.find((c)=>z(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Lr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Lr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Lr(t[r],i[r]))return!1;return!0}if(z(t)&&z(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Lr(t[e],i[e]))return!1}return!0}return!1}function z(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Lo(t,i){if(!vs(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ye(i,n)}catch{return null}}catch{return null}}async function Zo({name:t="",cwd:i,defaultConfig:r}){let n=i||me.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Ir(n,`${s}${c}`),h=await Lo(l,r);if(h!==null)return h}try{let s=Ir(n,"package.json");if(vs(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ye(r,c)}catch{}}}catch{}return r}function Mo(t,i={}){let r=Yr.cwd();while(r.includes("storage"))r=os(r,"..");let n=os(r,t||"");if(i?.relative)return ph(Yr.cwd(),n);return n}async function zo(){try{let t=await Zo({name:"clarity",defaultConfig:Jr,cwd:Yr.cwd(),endpoint:"",headers:{}});return{...Jr,...t}}catch{return Jr}}function q(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Go(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Gt<"u"){let t=Gt.type;if(t==="renderer"||t==="worker")return!1;return!!(Gt.versions&&(Gt.versions.node||Gt.versions.bun))}return!1}class il{async format(t){let i=await Go(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:wi.pid,hostname:i(),environment:wi.env.NODE_ENV||"development",platform:wi.platform,version:wi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wi.env.NODE_ENV||wi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Zr{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(t,i={}){this.name=t,this.config={...Ae},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new il,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??rt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Nr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Nr};return{...Nr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ae.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await to(this.config.logDirectory,ys.F_OK|ys.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await io(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ti.from(t);try{if(!Qn(this.currentLogFile))await te(this.currentLogFile,"",{mode:420});if(n=$s(this.currentLogFile,"a",420),Qh(n,c,{flag:"a"}),as(n),n!==void 0)Xn(n),n=void 0;if((await $i(this.currentLogFile)).size===0){if(await te(this.currentLogFile,c,{flag:"w",mode:420}),(await $i(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let o=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,o);let u=s*2**e;await new Promise(($)=>setTimeout($,u)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Xn(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,o=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yi(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 yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(q())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return vn(16).toString("hex")}generateKey(){return vn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=vn(16),n=Ph("aes-256-gcm",i,r),e=ti.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ti.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ms(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ti.from(ti.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(q())return;let t=await $i(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await $r(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await $i(r).catch(()=>null))try{if(await ws(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await yr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await te(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await $i(r).catch(()=>null))await ws(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await $r(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await yr(yi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=us(t),n=Xh(i),e=ms();await ro(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Qn(this.currentLogFile))try{let t=$s(this.currentLogFile,"r+");as(t),Xn(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await $r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await yr(yi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?L.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=rt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${L.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!q()){let h=ul[t],o=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:L.gray(s),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:L.green(s),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u),c){let $=c.split(`
2
- `);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:L.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!q()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
1
+ import{Aa as Sh,Ca as Fh,Da as Ch,pa as Y,ra as nr,sa as w,wa as gh,xa as Gf,za as zn}from"./chunk-zs1tyy8z.js";import ow from"node:dgram";import*as Hh from"node:fs/promises";import*as Lh from"node:path";import*as Qt from"node:process";import{spawn as _h}from"node:child_process";import*as Lt from"node:fs/promises";import{homedir as Pf}from"node:os";import*as Ot from"node:path";import*as U from"node:process";var Z={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};import{execSync as zi}from"node:child_process";import D from"node:fs/promises";import*as zf from"node:os";import{homedir as Gn}from"node:os";import{join as Q}from"node:path";import*as Yt from"node:process";import{createRequire as Kh}from"node:module";import pn from"node:os";import Pn from"node:path";import{existsSync as ls,statSync as cs}from"fs";import{existsSync as xh,mkdirSync as _w,readdirSync as Ww,readFileSync as kh,writeFileSync as Yw}from"fs";import{homedir as ai}from"os";import{dirname as Hw,resolve as Tt}from"path";import Vr from"process";import{existsSync as hs,statSync as us}from"fs";import{existsSync as me,mkdirSync as Dh,readdirSync as bh,writeFileSync as Vh}from"fs";import{homedir as $i}from"os";import{dirname as os,resolve as ht}from"path";import ci from"process";import{join as ph,relative as Ph,resolve as as}from"path";import Wr from"process";import{existsSync as Qs,mkdirSync as Dw,readdirSync as bw,writeFileSync as Vw}from"fs";import{homedir as vn}from"os";import{dirname as vw,resolve as ct}from"path";import bi from"process";import{join as vh,relative as Xh,resolve as $s}from"path";import Yr from"process";import{existsSync as tl,mkdirSync as r0,readdirSync as n0,writeFileSync as e0}from"fs";import{dirname as s0,resolve as Ir}from"path";import Ae from"process";import{Buffer as ti}from"buffer";import{createCipheriv as Qh,createDecipheriv as tu,randomBytes as Xn}from"crypto";import{closeSync as Qn,createReadStream as ys,createWriteStream as iu,existsSync as te,fsyncSync as ws,openSync as ms,writeFileSync as ru}from"fs";import{access as nu,constants as As,mkdir as eu,readdir as $r,rename as ds,stat as yi,unlink as yr,writeFile as ie}from"fs/promises";import{join as wi}from"path";import rt from"process";import{pipeline as fu}from"stream/promises";import{createGzip as Es}from"zlib";import mi from"process";import Gt from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as su,createDecipheriv as lu,randomBytes as re}from"crypto";import{closeSync as ne,createReadStream as Ts,createWriteStream as cu,existsSync as wr,fsyncSync as gs,openSync as Ss,writeFileSync as hu}from"fs";import{access as uu,constants as Cs,mkdir as ou,readdir as mr,rename as Rs,stat as Ai,unlink as Ar,writeFile as ee}from"fs/promises";import{isAbsolute as au,join as di,resolve as $u}from"path";import j from"process";import{pipeline as yu}from"stream/promises";import{createGzip as Bs}from"zlib";import Ei from"process";import qt from"process";import dr from"process";import{existsSync as Er}from"fs";import{resolve as fe}from"path";import{existsSync as wu}from"fs";import{existsSync as mu,readdirSync as Au}from"fs";import{extname as se,resolve as Us}from"path";import du from"process";import{join as Eu,relative as Tu,resolve as Fs}from"path";import Or from"process";import{Buffer as Mt}from"buffer";import{createCipheriv as gu,createDecipheriv as Su,randomBytes as le}from"crypto";import{closeSync as ce,createReadStream as Js,createWriteStream as Cu,existsSync as Tr,fsyncSync as Ns,openSync as js,writeFileSync as Ru}from"fs";import{access as Bu,constants as _s,mkdir as Uu,readdir as gr,rename as Ws,stat as Ti,unlink as Sr,writeFile as he}from"fs/promises";import{isAbsolute as Fu,join as gi,resolve as Ju}from"path";import _ from"process";import{pipeline as Nu}from"stream/promises";import{createGzip as Ys}from"zlib";import Si from"process";import Kt from"process";import Cr from"process";import{existsSync as Rr}from"fs";import{resolve as ue}from"path";import{existsSync as ju}from"fs";import{exec as Qo}from"node:child_process";import bs from"node:fs";import ta from"node:os";import Ut from"node:path";import Hl from"node:process";import{promisify as ia}from"node:util";import Ui from"node:crypto";import xt from"node:fs";import je from"node:path";import{execSync as Xs}from"node:child_process";import br from"node:os";var Uw=Kh(import.meta.url);class il{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!ls(t))return!0;return cs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=ls(r)?cs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class rl{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Hr=new il,_e=new rl,_u=Object.defineProperty,Wu=(t)=>t;function Yu(t,i){this[t]=Wu.bind(null,i)}var Iu=(t,i)=>{for(var r in i)_u(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Yu.bind(i,r)})},Ou=(t,i)=>()=>(t&&(i=t(t=0)),i),nl={};Iu(nl,{withErrorRecovery:()=>sl,tryLoadConfig:()=>eo,loadConfigWithResult:()=>ro,loadConfig:()=>ol,isRetryableError:()=>Pu,isConfigNotFoundError:()=>pu,isBunfigError:()=>ll,globalPerformanceMonitor:()=>vi,globalCache:()=>Ri,getEnvOrDefault:()=>vu,generateConfigTypes:()=>fo,defaultGeneratedDir:()=>El,defaultConfigDir:()=>dl,deepMergeWithArrayStrategy:()=>He,deepMerge:()=>cl,createLibraryConfig:()=>so,config:()=>no,bunfigPlugin:()=>lo,applyEnvVarsToConfig:()=>ki,TypeGenerationError:()=>Re,SchemaValidationError:()=>pi,PluginError:()=>Ue,PerformanceMonitor:()=>Ye,FileSystemError:()=>Ce,ErrorFactory:()=>ri,EnvVarError:()=>qr,EnvProcessor:()=>pr,ConfigValidator:()=>Le,ConfigValidationError:()=>ge,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>Se,ConfigLoader:()=>Ze,ConfigLoadError:()=>Vi,ConfigFileLoader:()=>Pr,ConfigCache:()=>We,CacheUtils:()=>$l,BunfigError:()=>mt,BrowserConfigError:()=>Be,ArrayMergeStrategies:()=>ml});class We{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!hs(t))return!0;return us(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=hs(r)?us(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Ye{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Hu(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function Lu(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Zu(t){return t.getStats().size*2}function Ie(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((f)=>G(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((f)=>G(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Lr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=Ie(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let s of r[n])if(G(s)&&"name"in s){if(!f.find((c)=>G(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((c)=>G(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Lr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Lr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Lr(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Lr(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Mu(t,i){if(!tl(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ie(i,n)}catch{return null}}catch{return null}}async function zu({name:t="",cwd:i,defaultConfig:r}){let n=i||Ae.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Ir(n,`${s}${c}`),h=await Mu(l,r);if(h!==null)return h}try{let s=Ir(n,"package.json");if(tl(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Ie(r,c)}catch{}}}catch{}return r}function Gu(t,i={}){let r=Yr.cwd();while(r.includes("storage"))r=$s(r,"..");let n=$s(r,t||"");if(i?.relative)return Xh(Yr.cwd(),n);return n}async function qu(){try{let t=await zu({name:"clarity",defaultConfig:Jr,cwd:Yr.cwd(),endpoint:"",headers:{}});return{...Jr,...t}}catch{return Jr}}function K(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ku(){if(Gt.env.NODE_ENV==="test"||Gt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Gt<"u"){let t=Gt.type;if(t==="renderer"||t==="worker")return!1;return!!(Gt.versions&&(Gt.versions.node||Gt.versions.bun))}return!1}class el{async format(t){let i=await Ku(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:mi.pid,hostname:i(),environment:mi.env.NODE_ENV||"development",platform:mi.platform,version:mi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mi.env.NODE_ENV||mi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Zr{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(t,i={}){this.name=t,this.config={...Ee},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new el,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??rt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Nr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Nr};return{...Nr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ee.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await nu(this.config.logDirectory,As.F_OK|As.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await eu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ti.from(t);try{if(!te(this.currentLogFile))await ie(this.currentLogFile,"",{mode:420});if(n=ms(this.currentLogFile,"a",420),ru(n,c,{flag:"a"}),ws(n),n!==void 0)Qn(n),n=void 0;if((await yi(this.currentLogFile)).size===0){if(await ie(this.currentLogFile,c,{flag:"w",mode:420}),(await yi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let o=s*2**e;await new Promise(($)=>setTimeout($,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Qn(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return wi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return wi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return wi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(K())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Xn(16).toString("hex")}generateKey(){return Xn(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Xn(16),n=Qh("aes-256-gcm",i,r),e=ti.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ti.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Es(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ti.from(ti.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(K())return;let t=await yi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await $r(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await yi(r).catch(()=>null))try{if(await ds(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await yr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ie(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await yi(r).catch(()=>null))await ds(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await $r(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await yr(wi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=ys(t),n=iu(i),e=Es();await fu(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),te(this.currentLogFile))try{let t=ms(this.currentLogFile,"r+");ws(t),Qn(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!K()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await $r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await yr(wi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?M.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=rt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${M.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!K()){let h=yl[t],u=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:M.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:M.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o),c){let $=c.split(`
2
+ `);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:M.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!K()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
3
3
  `;if(c)l+=`${c}
4
- `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!q()){let r=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:L.blue("◐"),tag:r,message:`${L.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
5
- `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let h=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:L.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!q())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!Qn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return us(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ti.isBuffer(t)?t:ti.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=vh("aes-256-gcm",r,e);return c.setAuthTag(f),ti.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q()}isServerMode(){return!q()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!q()){let f=t.split(`
6
- `),s=Math.max(...f.map((o)=>o.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((o)=>{let u=" ".repeat(s-o.length-2);return`│ ${o}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:L.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(c)})),h.forEach((o)=>console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(o),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(l),showTimestamp:!1}))}else if(!q())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
7
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(q())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${L.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();rt.stdin.removeListener("data",r);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let e=/%([sdijfo%])/g,f=0;if(r=t.replace(e,(s,c)=>{if(c==="%")return"%";if(f>=i.length)return s;let l=i[f++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return s}}),f<i.length)r+=` ${i.slice(f).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!q()){let e=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",f=L.blue("◐");console.error(`${f} ${e} ${L.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(t,i=""){if(!this.enabled||!this.fancy||q()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||q()||!rt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=L.green("━".repeat(n)),s=L.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=i||r===100?L.green("✓"):L.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=rt.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,rt.stdout.write(t.lastRenderedLine),i)rt.stdout.write(`
9
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||q()||!rt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await $r(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=yi(this.config.logDirectory,n);if(t.before)try{if((await $i(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await yr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Fr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&_(i[0])&&"id"in i[0]&&i[0].id===3&&_(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(_(i)&&_(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(_(t)&&"arr"in t&&Array.isArray(t.arr)&&_(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&_(i[0])&&_(t[0])){let n=[...i];for(let e of t)if(_(e)&&"name"in e){if(!n.find((f)=>_(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(_(e)&&"path"in e){if(!n.find((f)=>_(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Mr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!_(i)||!_(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(_(e)&&_(r[n]))r[n]=Fr(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&_(e[0])&&_(r[n][0])){let f=[...e];for(let s of r[n])if(_(s)&&"name"in s){if(!f.find((c)=>_(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(_(s)&&"path"in s){if(!f.find((c)=>_(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Mr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Ie(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:Fr(t,i);if(Array.isArray(t))return r==="replace"?i:Fr(t,i);if(!_(i)||!_(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=Fr(s,f);else if(_(f)&&_(s))n[e]=Ie(s,f,r);else n[e]=f}return n}function Mr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mr(t[r],i[r]))return!1;return!0}if(_(t)&&_(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Mr(t[e],i[e]))return!1}return!0}return!1}function _(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Br(t,i,r="replace"){if(!Ps(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Ie(i,e,r)}catch{return null}}catch{return null}}function qo(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${u.map($).join("_")}`,m=`${n}_${u.map((y)=>y.toUpperCase()).join("_")}`;if(r)et.info(`Checking environment variable ${a} for config ${t}.${u.join(".")}`);if(typeof o==="object"&&o!==null&&!Array.isArray(o))l[h]=f(o,u);else{let y=Di.env[a]||Di.env[m];if(y!==void 0){if(r)et.info(`Using environment variable ${y?a:m} for config ${t}.${u.join(".")}`);if(typeof o==="number")l[h]=Number(y);else if(typeof o==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(o))try{let d=JSON.parse(y);if(Array.isArray(d))l[h]=d;else l[h]=y.split(",").map((A)=>A.trim())}catch{l[h]=y.split(",").map((d)=>d.trim())}else l[h]=y}}}return l}return f(e)}async function Ko({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?qo(t,e,f):e,h=r||Di.cwd(),o=[".ts",".js",".mjs",".cjs",".json"];if(f)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let u=[t,`.${t}`].filter(Boolean),$=[`${t}.config`,`.${t}.config`].filter(Boolean),a=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([h,ct(h,"config"),ct(h,".config"),n?ct(h,n):void 0].filter(Boolean)));for(let d of y){if(f)et.info(`Searching for configuration in: ${d}`);let A=[ct(h,"config"),ct(h,".config")].concat(n?[ct(h,n)]:[]).includes(d)?[...u,...$,...a,...m]:[...$,...u,...m,...a];for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from: ${O}`);return H}}}if(t){let d=ct(Pn(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)et.info(`Checking user config directory: ${d}`);for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory: ${O}`);return H}}}if(t){let d=ct(Pn(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)et.info(`Checking user config directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory dotfile: ${O}`);return H}}}if(t){let d=Pn(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)et.info(`Checking user home directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ct(d,`${g}${I}`),H=await Br(O,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user home directory: ${O}`);return H}}}try{let d=ct(h,"package.json");if(Ps(d)){let A=await import(d),g=A[t];if(!g&&i){if(g=A[i],g&&f)et.success(`Using alias "${i}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(f)et.success(`Configuration loaded from package.json: ${g===A[t]?t:i}`);return Ie(l,g,c)}catch(I){if(f)et.warn("Failed to merge package.json config:",I)}}}catch(d){if(f)et.warn("Failed to load package.json:",d)}if(f)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function xo(t,i={}){let r=Wr.cwd();while(r.includes("storage"))r=hs(r,"..");let n=hs(r,t||"");if(i?.relative)return bh(Wr.cwd(),n);return n}async function ko(){try{let t=await Ko({name:"clarity",alias:"logging",defaultConfig:jr,cwd:Wr.cwd()});return{...jr,...t||{}}}catch{return jr}}function b(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Do(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof qt<"u"){let t=qt.type;if(t==="renderer"||t==="worker")return!1;return!!(qt.versions&&(qt.versions.node||qt.versions.bun))}return!1}class rl{async format(t){let i=await Do(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ai.pid,hostname:i(),environment:Ai.env.NODE_ENV||"development",platform:Ai.platform,version:Ai.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ai.env.NODE_ENV||Ai.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zr{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(t,i={}){this.name=t,this.config={...Ee},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new rl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{..._r,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{..._r};return{..._r,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ee.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!b()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await lo(this.config.logDirectory,Ts.F_OK|Ts.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await co(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Zt.from(t);try{if(!wr(this.currentLogFile))await ne(this.currentLogFile,"",{mode:420});if(n=Es(this.currentLogFile,"a",420),so(n,c,{flag:"a"}),As(n),n!==void 0)re(n),n=void 0;if((await mi(this.currentLogFile)).size===0){if(await ne(this.currentLogFile,c,{flag:"w",mode:420}),(await mi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let o=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,o);let u=s*2**e;await new Promise(($)=>setTimeout($,u)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{re(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,o=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return di(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 di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(b())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return ie(16).toString("hex")}generateKey(){return ie(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=ie(16),n=no("aes-256-gcm",i,r),e=Zt.isBuffer(t)?t:Zt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Zt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Ss(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Zt.from(Zt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(b())return;if(!this.shouldWriteToFile())return;let t=await mi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await mr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await mi(r).catch(()=>null))try{if(await gs(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await dr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ne(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await mi(r).catch(()=>null))await gs(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await mr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await dr(di(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=ds(t),n=fo(i),e=Ss();await uo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),wr(this.currentLogFile))try{let t=Es(this.currentLogFile,"r+");As(t),re(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await mr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await dr(di(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?R.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||b())return!1;let t=typeof N.env.NO_COLOR<"u",i=N.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof N.stderr<"u"&&N.stderr.isTTY||typeof N.stdout<"u"&&N.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=N.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${R.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=R.underline(R.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>R.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>R.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>R.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>R.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>R.strikethrough(n)),i}supportsHyperlinks(){if(b())return!1;let t=N.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=N.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(ho(i)||i.startsWith("./")||i.startsWith("../"))i=oo(i);else return null;return wr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":al[t],$=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:R.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:R.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
10
- `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:R.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
11
- `;if(c)o+=`${c}
12
- `;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!b()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!b()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!b()&&N.stdout.isTTY)N.stdout.write(`
13
- `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!b()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":R.blue("◐"),tag:r,message:`${R.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
14
- `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":R.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!b())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!wr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ds(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Zt.isBuffer(t)?t:Zt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=eo("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=Zt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
15
- `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:R.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(o),showTimestamp:!1}))}else if(!b())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
16
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(b())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${R.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let o=i[c++];switch(h){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${R.blue("◐")} `;console.error(`${c}${s} ${R.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
17
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=R.green("━".repeat(n)),s=R.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?R.green("✓"):R.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${R.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=N.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,N.stdout.write(t.lastRenderedLine),i)N.stdout.write(`
18
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||b()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await mr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=di(this.config.logDirectory,n);if(t.before)try{if((await mi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await dr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function nl(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function el(t){return t instanceof mt}function bo(t){return t instanceof Gr}function Vo(t){if(el(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class pr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Pi.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=Ar.env[l]||(h?Ar.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=Ar.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof qr)throw u;throw ri.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ri.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Ar.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
4
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!K()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:M.blue("◐"),tag:r,message:`${M.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
5
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!K()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:M.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!K())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(K())throw Error("createReadStream is not supported in browser environments");if(!te(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ys(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ti.isBuffer(t)?t:ti.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=tu("aes-256-gcm",r,e);return c.setAuthTag(f),ti.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return K()}isServerMode(){return!K()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!K()){let f=t.split(`
6
+ `),s=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((u)=>{let o=" ".repeat(s-u.length-2);return`│ ${u}${o} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(l),showTimestamp:!1}))}else if(!K())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
7
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(K())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${M.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();rt.stdin.removeListener("data",r);try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!1)}catch{}rt.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof rt.stdin.setRawMode==="function")rt.stdin.setRawMode(!0)}catch{}rt.stdin.resume(),rt.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let e=/%([sdijfo%])/g,f=0;if(r=t.replace(e,(s,c)=>{if(c==="%")return"%";if(f>=i.length)return s;let l=i[f++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return s}}),f<i.length)r+=` ${i.slice(f).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!K()){let e=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",f=M.blue("◐");console.error(`${f} ${e} ${M.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(t,i=""){if(!this.enabled||!this.fancy||K()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())return;rt.stdout.write(`${"\r".padEnd(rt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||K()||!rt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=M.green("━".repeat(n)),s=M.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||r===100?M.green("✓"):M.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=rt.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,rt.stdout.write(t.lastRenderedLine),i)rt.stdout.write(`
9
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||K()||!rt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(K()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await $r(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=wi(this.config.logDirectory,n);if(t.before)try{if((await yi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await yr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Fr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&W(i[0])&&"id"in i[0]&&i[0].id===3&&W(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(W(i)&&W(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(W(t)&&"arr"in t&&Array.isArray(t.arr)&&W(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&W(i[0])&&W(t[0])){let n=[...i];for(let e of t)if(W(e)&&"name"in e){if(!n.find((f)=>W(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(W(e)&&"path"in e){if(!n.find((f)=>W(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Mr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!W(i)||!W(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(W(e)&&W(r[n]))r[n]=Fr(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&W(e[0])&&W(r[n][0])){let f=[...e];for(let s of r[n])if(W(s)&&"name"in s){if(!f.find((c)=>W(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(W(s)&&"path"in s){if(!f.find((c)=>W(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Mr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Oe(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:Fr(t,i);if(Array.isArray(t))return r==="replace"?i:Fr(t,i);if(!W(i)||!W(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=Fr(s,f);else if(W(f)&&W(s))n[e]=Oe(s,f,r);else n[e]=f}return n}function Mr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mr(t[r],i[r]))return!1;return!0}if(W(t)&&W(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Mr(t[e],i[e]))return!1}return!0}return!1}function W(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Br(t,i,r="replace"){if(!Qs(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Oe(i,e,r)}catch{return null}}catch{return null}}function xu(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${o.map($).join("_")}`,m=`${n}_${o.map((y)=>y.toUpperCase()).join("_")}`;if(r)et.info(`Checking environment variable ${a} for config ${t}.${o.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[h]=f(u,o);else{let y=bi.env[a]||bi.env[m];if(y!==void 0){if(r)et.info(`Using environment variable ${y?a:m} for config ${t}.${o.join(".")}`);if(typeof u==="number")l[h]=Number(y);else if(typeof u==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(y);if(Array.isArray(A))l[h]=A;else l[h]=y.split(",").map((d)=>d.trim())}catch{l[h]=y.split(",").map((A)=>A.trim())}else l[h]=y}}}return l}return f(e)}async function ku({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?xu(t,e,f):e,h=r||bi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)et.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[t,`.${t}`].filter(Boolean),$=[`${t}.config`,`.${t}.config`].filter(Boolean),a=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([h,ct(h,"config"),ct(h,".config"),n?ct(h,n):void 0].filter(Boolean)));for(let A of y){if(f)et.info(`Searching for configuration in: ${A}`);let d=[ct(h,"config"),ct(h,".config")].concat(n?[ct(h,n)]:[]).includes(A)?[...o,...$,...a,...m]:[...$,...o,...m,...a];for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from: ${L}`);return H}}}if(t){let A=ct(vn(),".config",t),d=["config",`${t}.config`];if(i)d.push(`${i}.config`);if(f)et.info(`Checking user config directory: ${A}`);for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory: ${L}`);return H}}}if(t){let A=ct(vn(),".config"),d=[`.${t}.config`];if(i)d.push(`.${i}.config`);if(f)et.info(`Checking user config directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user config directory dotfile: ${L}`);return H}}}if(t){let A=vn(),d=[`.${t}.config`,`.${t}`];if(i)d.push(`.${i}.config`),d.push(`.${i}`);if(f)et.info(`Checking user home directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ct(A,`${g}${O}`),H=await Br(L,l,c);if(H!==null){if(f)et.success(`Configuration loaded from user home directory: ${L}`);return H}}}try{let A=ct(h,"package.json");if(Qs(A)){let d=await import(A),g=d[t];if(!g&&i){if(g=d[i],g&&f)et.success(`Using alias "${i}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(f)et.success(`Configuration loaded from package.json: ${g===d[t]?t:i}`);return Oe(l,g,c)}catch(O){if(f)et.warn("Failed to merge package.json config:",O)}}}catch(A){if(f)et.warn("Failed to load package.json:",A)}if(f)et.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function Du(t,i={}){let r=Wr.cwd();while(r.includes("storage"))r=as(r,"..");let n=as(r,t||"");if(i?.relative)return Ph(Wr.cwd(),n);return n}async function bu(){try{let t=await ku({name:"clarity",alias:"logging",defaultConfig:jr,cwd:Wr.cwd()});return{...jr,...t||{}}}catch{return jr}}function b(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Vu(){if(qt.env.NODE_ENV==="test"||qt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof qt<"u"){let t=qt.type;if(t==="renderer"||t==="worker")return!1;return!!(qt.versions&&(qt.versions.node||qt.versions.bun))}return!1}class fl{async format(t){let i=await Vu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ei.pid,hostname:i(),environment:Ei.env.NODE_ENV||"development",platform:Ei.platform,version:Ei.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ei.env.NODE_ENV||Ei.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zr{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(t,i={}){this.name=t,this.config={...Te},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new fl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{..._r,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{..._r};return{..._r,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Te.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!b()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await uu(this.config.logDirectory,Cs.F_OK|Cs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await ou(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Zt.from(t);try{if(!wr(this.currentLogFile))await ee(this.currentLogFile,"",{mode:420});if(n=Ss(this.currentLogFile,"a",420),hu(n,c,{flag:"a"}),gs(n),n!==void 0)ne(n),n=void 0;if((await Ai(this.currentLogFile)).size===0){if(await ee(this.currentLogFile,c,{flag:"w",mode:420}),(await Ai(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let o=s*2**e;await new Promise(($)=>setTimeout($,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{ne(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return di(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 di(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return di(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(b())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return re(16).toString("hex")}generateKey(){return re(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=re(16),n=su("aes-256-gcm",i,r),e=Zt.isBuffer(t)?t:Zt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Zt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Bs(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Zt.from(Zt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(b())return;if(!this.shouldWriteToFile())return;let t=await Ai(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await mr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ai(r).catch(()=>null))try{if(await Rs(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Ar(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ee(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ai(r).catch(()=>null))await Rs(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await mr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Ar(di(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Ts(t),n=cu(i),e=Bs();await yu(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),wr(this.currentLogFile))try{let t=Ss(this.currentLogFile,"r+");gs(t),ne(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await mr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Ar(di(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?R.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||b())return!1;let t=typeof j.env.NO_COLOR<"u",i=j.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=j.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${R.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=R.underline(R.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>R.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>R.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>R.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>R.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>R.strikethrough(n)),i}supportsHyperlinks(){if(b())return!1;let t=j.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=j.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(au(i)||i.startsWith("./")||i.startsWith("../"))i=$u(i);else return null;return wr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":wl[t],$=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:R.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:R.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
10
+ `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:R.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
11
+ `;if(c)u+=`${c}
12
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!b()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!b()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!b()&&j.stdout.isTTY)j.stdout.write(`
13
+ `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!b()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":R.blue("◐"),tag:r,message:`${R.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
14
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":R.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!b())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!wr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ts(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Zt.isBuffer(t)?t:Zt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=lu("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=Zt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
15
+ `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:R.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:R.cyan(u),showTimestamp:!1}))}else if(!b())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
16
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(b())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${R.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?R.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${R.blue("◐")} `;console.error(`${c}${s} ${R.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=R.green("━".repeat(n)),s=R.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?R.green("✓"):R.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${R.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=j.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,j.stdout.write(t.lastRenderedLine),i)j.stdout.write(`
18
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||b()||!j.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await mr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=di(this.config.logDirectory,n);if(t.before)try{if((await Ai(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ar(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function sl(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function ll(t){return t instanceof mt}function pu(t){return t instanceof Gr}function Pu(t){if(ll(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class pr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return vi.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=dr.env[l]||(h?dr.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=dr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof qr)throw o;throw ri.envVar(l,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ri.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(dr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
19
19
 
20
20
  `;for(let n of t)r+=`${n.key}
21
21
  `,r+=` Type: ${n.type}
@@ -27,25 +27,25 @@ import{Aa as Eh,Ca as Rh,Da as Th,pa as W,ra as rr,sa as w,wa as Ah,xa as zf,za
27
27
  `;r+=`| Variable | Type | Description | Example |
28
28
  `,r+=`|----------|------|-------------|----------|
29
29
  `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
30
- `;return r}}function po(t,i){let r=hl("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function fl(t,i,r={}){return sl(t,i,r,new WeakMap)}function sl(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return ll(t,i,e,n);if(!gt(i)||!gt(t))return i;return Qo(t,i,r,n)}function ll(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Po(t,i);case"smart":return vo(t,i,n);default:return i}return i}function Po(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>de(e,n)))r.push(n);return r}function vo(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(gt(i[0])&&gt(t[0]))return Xo(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Xo(t,i,r){let n=[...i];for(let e of t){if(!gt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>gt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Qo(t,i,r,n){let e=i;if(gt(e)&&n.has(e))return n.get(e);let f={...t};if(gt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(gt(c)&&gt(l))f[s]=sl(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ll(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Oe(t,i,r="replace"){return fl(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function de(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!de(t[r],i[r]))return!1;return!0}if(gt(t)&&gt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!de(t[e],i[e]))return!1}return!0}return!1}function gt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Pr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Ci.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Er(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new bi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new bi(t,Error("Configuration must export a valid object"),"unknown");let m={config:Oe(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Ci.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ri.configLoad(t,h):ri.configLoad(t,Error(String(h)))}};if(s)return Pi.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(ee(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return nl(async()=>{return Er(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Er(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=ee(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=ee(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Er(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class He{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await Pi.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!ao(i))throw new Vi(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Vi(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:yl},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Le{fileLoader=new Pr;envProcessor=new pr;validator=new He;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Ft.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Ft.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||ci.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(ht(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw ri.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?xi(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)Ft.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)Ft.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?xi(t,r,e):r,c=[ht(ai(),".config",t),ht(ai(),".config"),ai()];for(let l of c){if(e)Ft.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)Ft.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?xi(t,n,f):n;try{let l=ht(r,"package.json");if(!we(l))return null;let h=await import(l),o=h[t],u=t;if(!o&&i)o=h[i],u=i;if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)Ft.success(`Configuration loaded from package.json: ${u}`);return{config:Oe(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Ft.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:xi(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ri.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Ci.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Ci.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,ht(t,"config"),ht(t,".config"),i?ht(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(ht(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[ht(ai(),".config",t),ht(ai(),".config"),ai()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function _s(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function tu(t){return kt.loadConfig({...t,__strictErrorHandling:!0})}async function cl(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await kt.loadConfig(t);else n=await kt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Ft.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await kt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function iu(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await kt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&_s(r)))return(await kt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await kt.loadConfig({...t,cwd:t.cwd||ci.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&_s(i)))return(await kt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function ru(t,i,r="replace"){let n=new Pr;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function xi(t,i,r=!1){let n=new pr,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=ci.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}function nu(t){let i=ht(ci.cwd(),t.configDir),r=ht(ci.cwd(),t.generatedDir),n=ht(r,"config-types.ts");if(!we(cs(n)))Kh(cs(n),{recursive:!0,mode:511});let e=we(i)?xh(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Wu}
30
+ `;return r}}function vu(t,i){let r=al("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function cl(t,i,r={}){return hl(t,i,r,new WeakMap)}function hl(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return ul(t,i,e,n);if(!gt(i)||!gt(t))return i;return io(t,i,r,n)}function ul(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Xu(t,i);case"smart":return Qu(t,i,n);default:return i}return i}function Xu(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>de(e,n)))r.push(n);return r}function Qu(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(gt(i[0])&&gt(t[0]))return to(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function to(t,i,r){let n=[...i];for(let e of t){if(!gt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>gt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function io(t,i,r,n){let e=i;if(gt(e)&&n.has(e))return n.get(e);let f={...t};if(gt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(gt(c)&&gt(l))f[s]=hl(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ul(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function He(t,i,r="replace"){return cl(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function de(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!de(t[r],i[r]))return!1;return!0}if(gt(t)&&gt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!de(t[e],i[e]))return!1}return!0}return!1}function gt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Pr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Ri.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Er(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new Vi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new Vi(t,Error("Configuration must export a valid object"),"unknown");let m={config:He(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Ri.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ri.configLoad(t,h):ri.configLoad(t,Error(String(h)))}};if(s)return vi.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(fe(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return sl(async()=>{return Er(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Er(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=fe(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=fe(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Er(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class Le{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let u=[],o=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await vi.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!wu(i))throw new pi(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new pi(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:Al},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ze{fileLoader=new Pr;envProcessor=new pr;validator=new Le;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||u))throw l;if(o&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Ft.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Ft.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,o=f||ci.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(ht(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw ri.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?ki(t,e,s):e,u=this.getLocalDirectories(r,n);for(let o of u){if(s)Ft.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)Ft.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?ki(t,r,e):r,c=[ht($i(),".config",t),ht($i(),".config"),$i()];for(let l of c){if(e)Ft.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)Ft.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?ki(t,n,f):n;try{let l=ht(r,"package.json");if(!me(l))return null;let h=await import(l),u=h[t],o=t;if(!u&&i)u=h[i],o=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Ft.success(`Configuration loaded from package.json: ${o}`);return{config:He(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Ft.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:ki(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ri.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Ri.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Ri.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,ht(t,"config"),ht(t,".config"),i?ht(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(ht(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[ht($i(),".config",t),ht($i(),".config"),$i()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function Is(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function ro(t){return kt.loadConfig({...t,__strictErrorHandling:!0})}async function ol(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await kt.loadConfig(t);else n=await kt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Ft.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await kt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function no(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await kt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Is(r)))return(await kt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await kt.loadConfig({...t,cwd:t.cwd||ci.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Is(i)))return(await kt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function eo(t,i,r="replace"){let n=new Pr;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function ki(t,i,r=!1){let n=new pr,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=ci.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}function fo(t){let i=ht(ci.cwd(),t.configDir),r=ht(ci.cwd(),t.generatedDir),n=ht(r,"config-types.ts");if(!me(os(n)))Dh(os(n),{recursive:!0,mode:511});let e=me(i)?bh(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Oo}
31
31
  export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
32
- `;kh(n,f,{mode:438})}function eu(t){let i=null,r=null,n=()=>{if(!r)r=cl(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)Ft.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function fu(t){let i=Cs(wo.cwd(),t?.configDir||"./config");function r(){if(!$o(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=yo(i).filter((l)=>e.has(fe(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let o=fe(h).toLowerCase(),u=c.get(l);if(!u){c.set(l,h);continue}let $=fe(u).toLowerCase();if(f.indexOf(o)<f.indexOf($))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((l)=>l.base),s=f.length?f.map((l)=>`'${l}'`).join(" | "):"string",c=e.length?`{
33
- ${e.map((l)=>{let h=Cs(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${h}').default`}).join(`,
32
+ `;Vh(n,f,{mode:438})}function so(t){let i=null,r=null,n=()=>{if(!r)r=ol(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)Ft.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function lo(t){let i=Us(du.cwd(),t?.configDir||"./config");function r(){if(!mu(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Au(i).filter((l)=>e.has(se(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let u=se(h).toLowerCase(),o=c.get(l);if(!o){c.set(l,h);continue}let $=se(o).toLowerCase();if(f.indexOf(u)<f.indexOf($))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((l)=>l.base),s=f.length?f.map((l)=>`'${l}'`).join(" | "):"string",c=e.length?`{
33
+ ${e.map((l)=>{let h=Us(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${h}').default`}).join(`,
34
34
  `)}
35
35
  }`:"Record<string, any>";return`export type ConfigNames = ${s}
36
36
  export type ConfigByName = ${c}
37
37
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
38
38
  export type ConfigOf = Config
39
- `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var hl,Ci,Pi,ol,su,lu,Ws,Jr,Ae,nt,L,cu,Ys,hu,Is,ou,uu,oe,au,Os,Hs,ue,$u,yu,wu,mu,Nr,ul,du,et,Au,Eu,Ls,jr,Ee,V,R,Tu,Zs,gu,Ms,Su,Cu,ae,Ru,zs,Gs,Bu,$e,Uu,Fu,Ju,Nu,ju,_r,al,_u,Wu="0.15.6",mt,Gr,bi,Te,ge,qr,Se,Ce,Vi,Re,Be,ri,$l,yl,Ft,kt,wl,ml,Yu=Yo(async()=>{hl=import.meta.require,Ci=new _e,Pi=new We,ol={createKey:Io,isEquivalent:Oo,estimateMemoryUsage:Ho},su=Ir(me.cwd(),"config"),lu=Ir(me.cwd(),"src/generated"),Ws=Yr.env.CLARITY_LOG_DIR||Vh(Mo(),"logs"),Jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ws,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ae=await zo(),nt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},L=nt,cu=nt.red,Ys=nt.green,hu=nt.yellow,Is=nt.blue,ou=nt.magenta,uu=nt.cyan,oe=nt.white,au=nt.gray,Os=nt.bgRed,Hs=nt.bgYellow,ue=nt.bold,$u=nt.dim,yu=nt.italic,wu=nt.underline,mu=nt.reset,Nr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ul={debug:"\uD83D\uDD0D",info:Is("ℹ"),success:Ys("✓"),warning:Hs(oe(ue(" WARN "))),error:Os(oe(ue(" ERROR ")))},du=new Zr("stacks"),et=new Zr("bunfig",{showTags:!0}),Au=ct(Di.cwd(),"config"),Eu=ct(Di.cwd(),"src/generated"),Ls=Wr.env.CLARITY_LOG_DIR||Dh(xo(),"logs"),jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ls,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ee=await ko(),V={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},R=V,Tu=V.red,Zs=V.green,gu=V.yellow,Ms=V.blue,Su=V.magenta,Cu=V.cyan,ae=V.white,Ru=V.gray,zs=V.bgRed,Gs=V.bgYellow,Bu=V.bgGray,$e=V.bold,Uu=V.dim,Fu=V.italic,Ju=V.underline,Nu=V.strikethrough,ju=V.reset,_r={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},al={debug:"\uD83D\uDD0D",info:Ms("ℹ"),success:Zs("✓"),warning:Gs(ae($e(" WARN "))),error:zs(ae($e(" ERROR ")))},_u=new zr("stacks"),mt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Gr=class extends mt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},bi=class extends mt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Te=class extends mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},ge=class extends mt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qr=class extends mt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},Se=class extends mt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Ce=class extends mt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Vi=class extends mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},Re=class extends mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},Be=class extends mt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ri={configNotFound(t,i,r){return new Gr(t,i,r)},configLoad(t,i,r){return new bi(t,i,r)},configValidation(t,i,r){return new Te(t,i,r)},configMerge(t,i,r,n){return new ge(t,i,r,n)},envVar(t,i,r,n){return new qr(t,i,r,n)},fileSystem(t,i,r){return new Se(t,i,r)},typeGeneration(t,i,r){return new Ce(t,i,r)},schemaValidation(t,i,r){return new Vi(t,i,r)},browserConfig(t,i,r,n){return new Re(t,i,r,n)},plugin(t,i,r){return new Be(t,i,r)}},$l={replace:"replace",concat:"concat",smart:"smart"},yl=/^https?:\/\//,Ft=new zr("bunfig",{showTags:!0}),kt=new Le,wl=ht(ci.cwd(),"config"),ml=ht(ci.cwd(),"src/generated")});function Iu(t,i={}){let r=Or.cwd();while(r.includes("storage"))r=Rs(r,"..");let n=Rs(r,t||"");if(i?.relative)return Ao(Or.cwd(),n);return n}var Ou=Or.env.CLARITY_LOG_DIR||mo(Iu(),"logs"),dl={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ou,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Kr={...dl},V0=(async()=>{try{let{loadConfig:t}=await Yu().then(()=>tl),i=await t({name:"clarity",alias:"logging",defaultConfig:dl,cwd:Or.cwd()});if(i)Object.assign(Kr,i)}catch{}return Kr})();function p(){if(Kt.env.NODE_ENV==="test"||Kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Hu(){if(Kt.env.NODE_ENV==="test"||Kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Kt<"u"){let t=Kt.type;if(t==="renderer"||t==="worker")return!1;return!!(Kt.versions&&(Kt.versions.node||Kt.versions.bun))}return!1}class Al{async format(t){let i=await Hu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:gi.pid,hostname:i(),environment:gi.env.NODE_ENV||"development",platform:gi.platform,version:gi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:gi.env.NODE_ENV||gi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var tt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},U=tt,p0=tt.red,Lu=tt.green,P0=tt.yellow,Zu=tt.blue,v0=tt.magenta,X0=tt.cyan,qs=tt.white,Q0=tt.gray,Mu=tt.bgRed,zu=tt.bgYellow,tm=tt.bgGray,Ks=tt.bold,im=tt.dim,rm=tt.italic,nm=tt.underline,em=tt.strikethrough,fm=tt.reset,ye={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Gu={debug:"\uD83D\uDD0D",info:Zu("ℹ"),success:Lu("✓"),warning:zu(qs(Ks(" WARN "))),error:Mu(qs(Ks(" ERROR ")))};class vr{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(t,i={}){this.name=t,this.config={...Kr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Al,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ye,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ye};return{...ye,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Kr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Co(this.config.logDirectory,Js.F_OK|Js.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ro(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Mt.from(t);try{if(!Tr(this.currentLogFile))await ce(this.currentLogFile,"",{mode:420});if(n=Fs(this.currentLogFile,"a",420),So(n,c,{flag:"a"}),Us(n),n!==void 0)le(n),n=void 0;if((await Ei(this.currentLogFile)).size===0){if(await ce(this.currentLogFile,c,{flag:"w",mode:420}),(await Ei(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let o=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,o);let u=s*2**e;await new Promise(($)=>setTimeout($,u)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{le(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,o=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ti(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ti(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ti(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return se(16).toString("hex")}generateKey(){return se(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=se(16),n=Eo("aes-256-gcm",i,r),e=Mt.isBuffer(t)?t:Mt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Mt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=js(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Mt.from(Mt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await Ei(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await gr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ei(r).catch(()=>null))try{if(await Ns(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Sr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ce(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ei(r).catch(()=>null))await Ns(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await gr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Sr(Ti(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Bs(t),n=go(i),e=js();await Fo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Tr(this.currentLogFile))try{let t=Fs(this.currentLogFile,"r+");Us(t),le(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await gr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Sr(Ti(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?U.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof j.env.NO_COLOR<"u",i=j.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=j.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${U.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=U.underline(U.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>U.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>U.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>U.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>U.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>U.strikethrough(n)),i}supportsHyperlinks(){if(p())return!1;let t=j.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=j.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Bo(i)||i.startsWith("./")||i.startsWith("../"))i=Uo(i);else return null;return Tr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Gu[t],$=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:U.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:U.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
40
- `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:U.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
41
- `;if(c)o+=`${c}
42
- `;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!p()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!p()&&j.stdout.isTTY)j.stdout.write(`
43
- `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":U.blue("◐"),tag:r,message:`${U.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
44
- `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":U.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new vr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!Tr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Bs(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Mt.isBuffer(t)?t:Mt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=To("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=Mt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
45
- `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:U.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(o),showTimestamp:!1}))}else if(!p())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
46
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${U.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let o=i[c++];switch(h){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${U.blue("◐")} `;console.error(`${c}${s} ${U.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
47
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=U.green("━".repeat(n)),s=U.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?U.green("✓"):U.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${U.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=j.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,j.stdout.write(t.lastRenderedLine),i)j.stdout.write(`
48
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!j.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await gr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Ti(this.config.logDirectory,n);if(t.before)try{if((await Ei(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Sr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var sm=new vr("stacks");class jt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class El extends jt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class xr extends jt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class Tl extends jt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class gl extends jt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ze extends jt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class Sl extends jt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Cl extends jt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class kr extends jt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Rl extends jt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class Bl extends jt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Ri={configNotFound(t,i,r){return new El(t,i,r)},configLoad(t,i,r){return new xr(t,i,r)},configValidation(t,i,r){return new Tl(t,i,r)},configMerge(t,i,r,n){return new gl(t,i,r,n)},envVar(t,i,r,n){return new Ze(t,i,r,n)},fileSystem(t,i,r){return new Sl(t,i,r)},typeGeneration(t,i,r){return new Cl(t,i,r)},schemaValidation(t,i,r){return new kr(t,i,r)},browserConfig(t,i,r,n){return new Rl(t,i,r,n)},plugin(t,i,r){return new Bl(t,i,r)}};async function qu(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Me{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return je.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=Cr.env[l]||(h?Cr.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=Cr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof Ze)throw u;throw Ri.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Ri.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Cr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
39
+ `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var al,Ri,vi,$l,co,ho,Os,Jr,Ee,nt,M,uo,Hs,oo,Ls,ao,$o,oe,yo,Zs,Ms,ae,wo,mo,Ao,Eo,Nr,yl,To,et,go,So,zs,jr,Te,V,R,Co,Gs,Ro,qs,Bo,Uo,$e,Fo,Ks,xs,Jo,ye,No,jo,_o,Wo,Yo,_r,wl,Io,Oo="0.15.6",mt,Gr,Vi,ge,Se,qr,Ce,Re,pi,Be,Ue,ri,ml,Al,Ft,kt,dl,El,Ho=Ou(async()=>{al=import.meta.require,Ri=new We,vi=new Ye,$l={createKey:Hu,isEquivalent:Lu,estimateMemoryUsage:Zu},co=Ir(Ae.cwd(),"config"),ho=Ir(Ae.cwd(),"src/generated"),Os=Yr.env.CLARITY_LOG_DIR||vh(Gu(),"logs"),Jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Os,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ee=await qu(),nt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},M=nt,uo=nt.red,Hs=nt.green,oo=nt.yellow,Ls=nt.blue,ao=nt.magenta,$o=nt.cyan,oe=nt.white,yo=nt.gray,Zs=nt.bgRed,Ms=nt.bgYellow,ae=nt.bold,wo=nt.dim,mo=nt.italic,Ao=nt.underline,Eo=nt.reset,Nr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},yl={debug:"\uD83D\uDD0D",info:Ls("ℹ"),success:Hs("✓"),warning:Ms(oe(ae(" WARN "))),error:Zs(oe(ae(" ERROR ")))},To=new Zr("stacks"),et=new Zr("bunfig",{showTags:!0}),go=ct(bi.cwd(),"config"),So=ct(bi.cwd(),"src/generated"),zs=Wr.env.CLARITY_LOG_DIR||ph(Du(),"logs"),jr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zs,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Te=await bu(),V={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},R=V,Co=V.red,Gs=V.green,Ro=V.yellow,qs=V.blue,Bo=V.magenta,Uo=V.cyan,$e=V.white,Fo=V.gray,Ks=V.bgRed,xs=V.bgYellow,Jo=V.bgGray,ye=V.bold,No=V.dim,jo=V.italic,_o=V.underline,Wo=V.strikethrough,Yo=V.reset,_r={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},wl={debug:"\uD83D\uDD0D",info:qs("ℹ"),success:Gs("✓"),warning:xs($e(ye(" WARN "))),error:Ks($e(ye(" ERROR ")))},Io=new zr("stacks"),mt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Gr=class extends mt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},Vi=class extends mt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},ge=class extends mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},Se=class extends mt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},qr=class extends mt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},Ce=class extends mt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Re=class extends mt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},pi=class extends mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},Be=class extends mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},Ue=class extends mt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ri={configNotFound(t,i,r){return new Gr(t,i,r)},configLoad(t,i,r){return new Vi(t,i,r)},configValidation(t,i,r){return new ge(t,i,r)},configMerge(t,i,r,n){return new Se(t,i,r,n)},envVar(t,i,r,n){return new qr(t,i,r,n)},fileSystem(t,i,r){return new Ce(t,i,r)},typeGeneration(t,i,r){return new Re(t,i,r)},schemaValidation(t,i,r){return new pi(t,i,r)},browserConfig(t,i,r,n){return new Be(t,i,r,n)},plugin(t,i,r){return new Ue(t,i,r)}},ml={replace:"replace",concat:"concat",smart:"smart"},Al=/^https?:\/\//,Ft=new zr("bunfig",{showTags:!0}),kt=new Ze,dl=ht(ci.cwd(),"config"),El=ht(ci.cwd(),"src/generated")});function Lo(t,i={}){let r=Or.cwd();while(r.includes("storage"))r=Fs(r,"..");let n=Fs(r,t||"");if(i?.relative)return Tu(Or.cwd(),n);return n}var Zo=Or.env.CLARITY_LOG_DIR||Eu(Lo(),"logs"),Tl={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Zo,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Kr={...Tl},v0=(async()=>{try{let{loadConfig:t}=await Ho().then(()=>nl),i=await t({name:"clarity",alias:"logging",defaultConfig:Tl,cwd:Or.cwd()});if(i)Object.assign(Kr,i)}catch{}return Kr})();function p(){if(Kt.env.NODE_ENV==="test"||Kt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Mo(){if(Kt.env.NODE_ENV==="test"||Kt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Kt<"u"){let t=Kt.type;if(t==="renderer"||t==="worker")return!1;return!!(Kt.versions&&(Kt.versions.node||Kt.versions.bun))}return!1}class gl{async format(t){let i=await Mo(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Si.pid,hostname:i(),environment:Si.env.NODE_ENV||"development",platform:Si.platform,version:Si.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Si.env.NODE_ENV||Si.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var tt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},F=tt,X0=tt.red,zo=tt.green,Q0=tt.yellow,Go=tt.blue,tm=tt.magenta,im=tt.cyan,ks=tt.white,rm=tt.gray,qo=tt.bgRed,Ko=tt.bgYellow,nm=tt.bgGray,Ds=tt.bold,em=tt.dim,fm=tt.italic,sm=tt.underline,lm=tt.strikethrough,cm=tt.reset,we={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xo={debug:"\uD83D\uDD0D",info:Go("ℹ"),success:zo("✓"),warning:Ko(ks(Ds(" WARN "))),error:qo(ks(Ds(" ERROR ")))};class vr{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(t,i={}){this.name=t,this.config={...Kr},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new gl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...we,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...we};return{...we,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Kr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Bu(this.config.logDirectory,_s.F_OK|_s.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Uu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Mt.from(t);try{if(!Tr(this.currentLogFile))await he(this.currentLogFile,"",{mode:420});if(n=js(this.currentLogFile,"a",420),Ru(n,c,{flag:"a"}),Ns(n),n!==void 0)ce(n),n=void 0;if((await Ti(this.currentLogFile)).size===0){if(await he(this.currentLogFile,c,{flag:"w",mode:420}),(await Ti(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let o=s*2**e;await new Promise(($)=>setTimeout($,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{ce(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return gi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return gi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return le(16).toString("hex")}generateKey(){return le(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=le(16),n=gu("aes-256-gcm",i,r),e=Mt.isBuffer(t)?t:Mt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Mt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Ys(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Mt.from(Mt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await Ti(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await gr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ti(r).catch(()=>null))try{if(await Ws(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Sr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await he(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ti(r).catch(()=>null))await Ws(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await gr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Sr(gi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Js(t),n=Cu(i),e=Ys();await Nu(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Tr(this.currentLogFile))try{let t=js(this.currentLogFile,"r+");Ns(t),ce(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await gr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Sr(gi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=_.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${F.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=F.underline(F.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>F.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>F.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>F.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>F.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>F.strikethrough(n)),i}supportsHyperlinks(){if(p())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=_.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Fu(i)||i.startsWith("./")||i.startsWith("../"))i=Ju(i);else return null;return Tr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":xo[t],$=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:F.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:F.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
40
+ `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:F.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
41
+ `;if(c)u+=`${c}
42
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!p()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!p()&&_.stdout.isTTY)_.stdout.write(`
43
+ `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":F.blue("◐"),tag:r,message:`${F.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
44
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!p())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new vr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!Tr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Js(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Mt.isBuffer(t)?t:Mt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Su("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=Mt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
45
+ `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:F.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(u),showTimestamp:!1}))}else if(!p())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
46
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(p())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${F.blue("◐")} `;console.error(`${c}${s} ${F.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=F.green("━".repeat(n)),s=F.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=_.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
48
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||p()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await gr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=gi(this.config.logDirectory,n);if(t.before)try{if((await Ti(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Sr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var hm=new vr("stacks");class jt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class Sl extends jt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class xr extends jt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class Cl extends jt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Rl extends jt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Me extends jt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class Bl extends jt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ul extends jt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class kr extends jt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Fl extends jt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class Jl extends jt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Bi={configNotFound(t,i,r){return new Sl(t,i,r)},configLoad(t,i,r){return new xr(t,i,r)},configValidation(t,i,r){return new Cl(t,i,r)},configMerge(t,i,r,n){return new Rl(t,i,r,n)},envVar(t,i,r,n){return new Me(t,i,r,n)},fileSystem(t,i,r){return new Bl(t,i,r)},typeGeneration(t,i,r){return new Ul(t,i,r)},schemaValidation(t,i,r){return new kr(t,i,r)},browserConfig(t,i,r,n){return new Fl(t,i,r,n)},plugin(t,i,r){return new Jl(t,i,r)}};async function ko(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class ze{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return _e.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=Cr.env[l]||(h?Cr.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=Cr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof Me)throw o;throw Bi.envVar(l,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Bi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Cr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
49
49
 
50
50
  `;for(let n of t)r+=`${n.key}
51
51
  `,r+=` Type: ${n.type}
@@ -57,30 +57,30 @@ export type ConfigOf = Config
57
57
  `;r+=`| Variable | Type | Description | Example |
58
58
  `,r+=`|----------|------|-------------|----------|
59
59
  `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
60
- `;return r}}function Ku(t,i,r={}){return Ul(t,i,r,new WeakMap)}function Ul(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Fl(t,i,e,n);if(!St(i)||!St(t))return i;return bu(t,i,r,n)}function Fl(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return xu(t,i);case"smart":return ku(t,i,n);default:return i}return i}function xu(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Ue(e,n)))r.push(n);return r}function ku(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(St(i[0])&&St(t[0]))return Du(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Du(t,i,r){let n=[...i];for(let e of t){if(!St(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>St(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function bu(t,i,r,n){let e=i;if(St(e)&&n.has(e))return n.get(e);let f={...t};if(St(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(St(c)&&St(l))f[s]=Ul(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Fl(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Jl(t,i,r="replace"){return Ku(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ue(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Ue(t[r],i[r]))return!1;return!0}if(St(t)&&St(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Ue(t[e],i[e]))return!1}return!0}return!1}function St(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Nl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Hr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Rr(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new xr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new xr(t,Error("Configuration must export a valid object"),"unknown");let m={config:Jl(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Hr.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?Ri.configLoad(t,h):Ri.configLoad(t,Error(String(h)))}};if(s)return je.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(he(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return qu(async()=>{return Rr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Rr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=he(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=he(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Rr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var Vu=/^https?:\/\//;class jl{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await je.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Jo(i))throw new kr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new kr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:Vu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var zt=new vr("bunfig",{showTags:!0});function pu(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class _l{fileLoader=new Nl;envProcessor=new Me;validator=new jl;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)zt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw zt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||Vr.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(Tt(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw Ri.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${pu(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Ur(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)zt.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)zt.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Ur(t,r,e):r,c=[Tt(ui(),".config",t),Tt(ui(),".config"),ui()];for(let l of c){if(e)zt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)zt.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Ur(t,n,f):n;try{let l=Tt(r,"package.json");if(!Gh(l))return null;let h={};try{h=JSON.parse(qh(l,"utf8"))}catch($){if(f)zt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let o=h[t],u=t;if(!o&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){o=h[a],u=a;break}}}if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)zt.success(`Configuration loaded from package.json: ${u}`);return{config:Jl(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)zt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ur(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Ri.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Hr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Hr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Tt(t,"config"),Tt(t,".config"),i?Tt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Tt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Tt(ui(),".config",t),Tt(ui(),".config"),ui()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var lm=new _l;function Ur(t,i,r=!1){let n=new Me,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=Vr.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}var cm=Tt(Vr.cwd(),"config"),hm=Tt(Vr.cwd(),"src/generated"),Wl={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:pn.join(Vn.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:pn.join(Vn.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:pn.join(Vn.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},x=Wl,Jt={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"};var T={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Si={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function Fe(t,i){let r=[];function n(e){let f;try{f=xs.readdirSync(e)}catch{return}for(let s of f){let c=Ut.join(e,s);try{if(xs.statSync(c).isDirectory())n(c);else if(s===i)r.push(e)}catch{continue}}}return n(t),r}function E(t,i,r){if(r||x.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Qu=Xu(Pu);function Il(){return Yl.env.SUDO_PASSWORD}var ks="[redacted]",ta=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),ia=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function ra(t){let i=t.toLowerCase();return ta.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Dr(t){if(Array.isArray(t))return t.map((r)=>Dr(r));if(typeof t==="string")return ia.test(t)?ks:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(ra(r)){i[r]=ks;continue}i[r]=Dr(n)}return i}function Xr(t){return JSON.stringify(Dr(t))}function na(t){let i=Il();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function ii(t,i={}){let r=na(t);try{let{stdout:n,stderr:e}=await Qu(r,{cwd:i.cwd||Yl.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
61
- Error: ${n.message}`);throw e.stack=n.stack,e}}function Ol(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function ze(t){let i=Ut.join(vu.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:x.basePath&&x.basePath.trim()!==""?x.basePath:i,n=t.certPath?Ut.isAbsolute(t.certPath)?t.certPath:Ut.join(r,t.certPath):Ut.join(r,x.certPath),e=t.keyPath?Ut.isAbsolute(t.keyPath)?t.keyPath:Ut.join(r,t.keyPath):Ut.join(r,x.keyPath),f=t.caCertPath?Ut.isAbsolute(t.caCertPath)?t.caCertPath:Ut.join(r,t.caCertPath):Ut.join(r,x.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function Hl(t){let i=[],r=new Set;if(t.domain)r.add(t.domain);if(t.domains?.length)t.domains.forEach((n)=>r.add(n));for(let n of r)i.push({type:2,value:n});if(t.altNameIPs?.length)for(let n of t.altNameIPs)i.push({type:7,ip:n});if(t.altNameURIs?.length)for(let n of t.altNameURIs)i.push({type:6,value:n});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return E(T.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function Ge(t){let i=t.notBeforeDays??Jt.DEFAULT_NOT_BEFORE_DAYS,r=t.validityDays??(t.validityYears?t.validityYears*365:Jt.DEFAULT_VALIDITY_DAYS);E(T.CERT,"Calculating certificate validity dates",t.verbose);let n=new Date(Date.now()-86400*i*1000),e=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),E(T.CERT,`Validity period: ${n.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:n,notAfter:e}}var Nt={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},ot={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"};function ki(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function At(t,i){let r=ki(i.length);return Buffer.concat([Buffer.from([t]),r,i])}function pi(t){let i=t.split(".").map(Number),r=[];r.push(40*i[0]+i[1]);for(let n=2;n<i.length;n++){let e=i[n],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;r.push(...f)}return At(Nt.OID,Buffer.from(r))}function Je(t){let i;if(typeof t==="bigint"){let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return At(Nt.INTEGER,i)}function Ll(t,i=0){return At(Nt.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function Zl(t){return At(Nt.OCTET_STRING,t)}function dt(...t){return At(Nt.SEQUENCE,Buffer.concat(t))}function ea(...t){return At(Nt.SET,Buffer.concat(t))}function fa(t){return At(Nt.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function sa(t){return At(Nt.UTF8_STRING,Buffer.from(t,"utf8"))}function la(){return Buffer.from([Nt.NULL,0])}function Ds(t,i,r=!0){let n=160|t|(r?0:0),e=ki(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function bs(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return At(Nt.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(i%100).toString().padStart(2,"0"),n=(t.getUTCMonth()+1).toString().padStart(2,"0"),e=t.getUTCDate().toString().padStart(2,"0"),f=t.getUTCHours().toString().padStart(2,"0"),s=t.getUTCMinutes().toString().padStart(2,"0"),c=t.getUTCSeconds().toString().padStart(2,"0"),l=`${r}${n}${e}${f}${s}${c}Z`;return At(Nt.UTC_TIME,Buffer.from(l,"ascii"))}}function ca(t,i){return dt(bs(t),bs(i))}function Vs(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=ot.COMMON_NAME;break;case"C":n=ot.COUNTRY;break;case"L":n=ot.LOCALITY;break;case"ST":n=ot.STATE;break;case"O":n=ot.ORGANIZATION;break;case"OU":n=ot.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?fa(r.value):sa(r.value),f=dt(pi(n),e);i.push(ea(f))}return dt(...i)}function Ml(t){return dt(pi(t),la())}function ha(t){return t.export({type:"spki",format:"der"})}function oa(t){if(t.includes(":")){let i=t;if(t.includes("::")){let e=t.split("::"),f=e[0]?e[0].split(":"):[],s=e[1]?e[1].split(":"):[],c=8-f.length-s.length,l=Array.from({length:c},()=>"0");i=[...f,...l,...s].join(":")}let r=i.split(":"),n=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(r[e]||"0",16);n.writeUInt16BE(f,e*2)}return n}else{let i=t.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(i)}}function ua(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=ki(r.value.length);i.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=oa(r.ip),e=ki(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=ki(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return dt(...i)}function aa(t,i){if(t){if(i!==void 0)return dt(At(1,Buffer.from([255])),Je(i));return dt(At(1,Buffer.from([255])))}return dt()}function $a(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let r=0,n=i;while(n>0&&(n&1)===0)r++,n>>=1;if(i===0)r=7;return Ll(Buffer.from([i]),r)}function ya(t){let i=[];if(t.serverAuth)i.push(pi(ot.SERVER_AUTH));if(t.clientAuth)i.push(pi(ot.CLIENT_AUTH));return dt(...i)}function Ki(t,i,r){let n=[pi(t)];if(i)n.push(At(1,Buffer.from([255])));return n.push(Zl(r)),dt(...n)}function wa(t){let i=[];if(i.push(Ds(0,Je(2))),i.push(Je(t.serialNumber)),i.push(Ml(ot.SHA256_WITH_RSA)),i.push(Vs(t.issuer)),i.push(ca(t.notBefore,t.notAfter)),i.push(Vs(t.subject)),i.push(ha(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(Ki(ot.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,aa(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(Ki(ot.KEY_USAGE,t.extensions.keyUsage.critical??!0,$a(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(Ki(ot.EXTENDED_KEY_USAGE,!1,ya(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(Ki(ot.SUBJECT_ALT_NAME,!1,ua(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(Ki(ot.SUBJECT_KEY_IDENTIFIER,!1,Zl(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(Ds(3,dt(...r)))}return dt(...i)}function ma(t,i){let r=Bi.createSign("SHA256");r.update(t);let n=r.sign(i);return dt(t,Ml(ot.SHA256_WITH_RSA),Ll(n))}function da(t,i){let r=t.toString("base64"),n=[];for(let e=0;e<r.length;e+=64)n.push(r.slice(e,e+64));return`-----BEGIN ${i}-----
60
+ `;return r}}function Do(t,i,r={}){return Nl(t,i,r,new WeakMap)}function Nl(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return jl(t,i,e,n);if(!St(i)||!St(t))return i;return Po(t,i,r,n)}function jl(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return bo(t,i);case"smart":return Vo(t,i,n);default:return i}return i}function bo(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Fe(e,n)))r.push(n);return r}function Vo(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(St(i[0])&&St(t[0]))return po(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function po(t,i,r){let n=[...i];for(let e of t){if(!St(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>St(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Po(t,i,r,n){let e=i;if(St(e)&&n.has(e))return n.get(e);let f={...t};if(St(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(St(c)&&St(l))f[s]=Nl(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=jl(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function _l(t,i,r="replace"){return Do(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Fe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Fe(t[r],i[r]))return!1;return!0}if(St(t)&&St(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Fe(t[e],i[e]))return!1}return!0}return!1}function St(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Wl{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Hr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Rr(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new xr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new xr(t,Error("Configuration must export a valid object"),"unknown");let m={config:_l(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Hr.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?Bi.configLoad(t,h):Bi.configLoad(t,Error(String(h)))}};if(s)return _e.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(ue(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return ko(async()=>{return Rr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Rr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=ue(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=ue(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Rr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var vo=/^https?:\/\//;class Yl{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let u=[],o=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await _e.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!ju(i))throw new kr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new kr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:vo},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var zt=new vr("bunfig",{showTags:!0});function Xo(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class Il{fileLoader=new Wl;envProcessor=new ze;validator=new Yl;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||u))throw l;if(o&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)zt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw zt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,o=f||Vr.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(Tt(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw Bi.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),warnings:[`No configuration file found for "${n}"${Xo(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Ur(t,e,s):e,u=this.getLocalDirectories(r,n);for(let o of u){if(s)zt.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)zt.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Ur(t,r,e):r,c=[Tt(ai(),".config",t),Tt(ai(),".config"),ai()];for(let l of c){if(e)zt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)zt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Ur(t,n,f):n;try{let l=Tt(r,"package.json");if(!xh(l))return null;let h={};try{h=JSON.parse(kh(l,"utf8"))}catch($){if(f)zt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let u=h[t],o=t;if(!u&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){u=h[a],o=a;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)zt.success(`Configuration loaded from package.json: ${o}`);return{config:_l(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)zt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ur(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Bi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Hr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Hr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Tt(t,"config"),Tt(t,".config"),i?Tt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Tt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Tt(ai(),".config",t),Tt(ai(),".config"),ai()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var um=new Il;function Ur(t,i,r=!1){let n=new ze,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=Vr.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}var om=Tt(Vr.cwd(),"config"),am=Tt(Vr.cwd(),"src/generated"),Ol={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:Pn.join(pn.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Pn.join(pn.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Pn.join(pn.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},k=Ol,Jt={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"};var T={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Ci={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function Je(t,i){let r=[];function n(e){let f;try{f=bs.readdirSync(e)}catch{return}for(let s of f){let c=Ut.join(e,s);try{if(bs.statSync(c).isDirectory())n(c);else if(s===i)r.push(e)}catch{continue}}}return n(t),r}function E(t,i,r){if(r||k.verbose)console.debug(`[tlsx:${t}] ${i}`)}var ra=ia(Qo);function Ll(){return Hl.env.SUDO_PASSWORD}var Vs="[redacted]",na=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),ea=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function fa(t){let i=t.toLowerCase();return na.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Dr(t){if(Array.isArray(t))return t.map((r)=>Dr(r));if(typeof t==="string")return ea.test(t)?Vs:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(fa(r)){i[r]=Vs;continue}i[r]=Dr(n)}return i}function Xr(t){return JSON.stringify(Dr(t))}function sa(t){let i=Ll();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function ii(t,i={}){let r=sa(t);try{let{stdout:n,stderr:e}=await ra(r,{cwd:i.cwd||Hl.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
61
+ Error: ${n.message}`);throw e.stack=n.stack,e}}function Zl(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function Ge(t){let i=Ut.join(ta.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:k.basePath&&k.basePath.trim()!==""?k.basePath:i,n=t.certPath?Ut.isAbsolute(t.certPath)?t.certPath:Ut.join(r,t.certPath):Ut.join(r,k.certPath),e=t.keyPath?Ut.isAbsolute(t.keyPath)?t.keyPath:Ut.join(r,t.keyPath):Ut.join(r,k.keyPath),f=t.caCertPath?Ut.isAbsolute(t.caCertPath)?t.caCertPath:Ut.join(r,t.caCertPath):Ut.join(r,k.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function Ml(t){let i=[],r=new Set;if(t.domain)r.add(t.domain);if(t.domains?.length)t.domains.forEach((n)=>r.add(n));for(let n of r)i.push({type:2,value:n});if(t.altNameIPs?.length)for(let n of t.altNameIPs)i.push({type:7,ip:n});if(t.altNameURIs?.length)for(let n of t.altNameURIs)i.push({type:6,value:n});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return E(T.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function qe(t){let i=t.notBeforeDays??Jt.DEFAULT_NOT_BEFORE_DAYS,r=t.validityDays??(t.validityYears?t.validityYears*365:Jt.DEFAULT_VALIDITY_DAYS);E(T.CERT,"Calculating certificate validity dates",t.verbose);let n=new Date(Date.now()-86400*i*1000),e=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),E(T.CERT,`Validity period: ${n.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:n,notAfter:e}}var Nt={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},ut={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"};function Di(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function dt(t,i){let r=Di(i.length);return Buffer.concat([Buffer.from([t]),r,i])}function Pi(t){let i=t.split(".").map(Number),r=[];r.push(40*i[0]+i[1]);for(let n=2;n<i.length;n++){let e=i[n],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;r.push(...f)}return dt(Nt.OID,Buffer.from(r))}function Ne(t){let i;if(typeof t==="bigint"){let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return dt(Nt.INTEGER,i)}function zl(t,i=0){return dt(Nt.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function Gl(t){return dt(Nt.OCTET_STRING,t)}function At(...t){return dt(Nt.SEQUENCE,Buffer.concat(t))}function la(...t){return dt(Nt.SET,Buffer.concat(t))}function ca(t){return dt(Nt.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function ha(t){return dt(Nt.UTF8_STRING,Buffer.from(t,"utf8"))}function ua(){return Buffer.from([Nt.NULL,0])}function ps(t,i,r=!0){let n=160|t|(r?0:0),e=Di(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function Ps(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return dt(Nt.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(i%100).toString().padStart(2,"0"),n=(t.getUTCMonth()+1).toString().padStart(2,"0"),e=t.getUTCDate().toString().padStart(2,"0"),f=t.getUTCHours().toString().padStart(2,"0"),s=t.getUTCMinutes().toString().padStart(2,"0"),c=t.getUTCSeconds().toString().padStart(2,"0"),l=`${r}${n}${e}${f}${s}${c}Z`;return dt(Nt.UTC_TIME,Buffer.from(l,"ascii"))}}function oa(t,i){return At(Ps(t),Ps(i))}function vs(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=ut.COMMON_NAME;break;case"C":n=ut.COUNTRY;break;case"L":n=ut.LOCALITY;break;case"ST":n=ut.STATE;break;case"O":n=ut.ORGANIZATION;break;case"OU":n=ut.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?ca(r.value):ha(r.value),f=At(Pi(n),e);i.push(la(f))}return At(...i)}function ql(t){return At(Pi(t),ua())}function aa(t){return t.export({type:"spki",format:"der"})}function $a(t){if(t.includes(":")){let i=t;if(t.includes("::")){let e=t.split("::"),f=e[0]?e[0].split(":"):[],s=e[1]?e[1].split(":"):[],c=8-f.length-s.length,l=Array.from({length:c},()=>"0");i=[...f,...l,...s].join(":")}let r=i.split(":"),n=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(r[e]||"0",16);n.writeUInt16BE(f,e*2)}return n}else{let i=t.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(i)}}function ya(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=Di(r.value.length);i.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=$a(r.ip),e=Di(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=Di(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return At(...i)}function wa(t,i){if(t){if(i!==void 0)return At(dt(1,Buffer.from([255])),Ne(i));return At(dt(1,Buffer.from([255])))}return At()}function ma(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let r=0,n=i;while(n>0&&(n&1)===0)r++,n>>=1;if(i===0)r=7;return zl(Buffer.from([i]),r)}function Aa(t){let i=[];if(t.serverAuth)i.push(Pi(ut.SERVER_AUTH));if(t.clientAuth)i.push(Pi(ut.CLIENT_AUTH));return At(...i)}function xi(t,i,r){let n=[Pi(t)];if(i)n.push(dt(1,Buffer.from([255])));return n.push(Gl(r)),At(...n)}function da(t){let i=[];if(i.push(ps(0,Ne(2))),i.push(Ne(t.serialNumber)),i.push(ql(ut.SHA256_WITH_RSA)),i.push(vs(t.issuer)),i.push(oa(t.notBefore,t.notAfter)),i.push(vs(t.subject)),i.push(aa(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(xi(ut.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,wa(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(xi(ut.KEY_USAGE,t.extensions.keyUsage.critical??!0,ma(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(xi(ut.EXTENDED_KEY_USAGE,!1,Aa(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(xi(ut.SUBJECT_ALT_NAME,!1,ya(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(xi(ut.SUBJECT_KEY_IDENTIFIER,!1,Gl(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(ps(3,At(...r)))}return At(...i)}function Ea(t,i){let r=Ui.createSign("SHA256");r.update(t);let n=r.sign(i);return At(t,ql(ut.SHA256_WITH_RSA),zl(n))}function Ta(t,i){let r=t.toString("base64"),n=[];for(let e=0;e<r.length;e+=64)n.push(r.slice(e,e+64));return`-----BEGIN ${i}-----
62
62
  ${n.join(`
63
63
  `)}
64
64
  -----END ${i}-----
65
- `}function qe(){return Bi.randomBytes(20)}function zl(t=2048){let{privateKey:i,publicKey:r}=Bi.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function Aa(t){let i=t.export({type:"spki",format:"der"});return Bi.createHash("sha1").update(i).digest()}function Gl(t){let i={serialNumber:t.serialNumber||qe(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:Aa(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let r=wa(i),n=ma(r,t.signingKey);return{certificate:da(n,"CERTIFICATE"),certificateDer:n}}function ql(t){return t.export({type:"pkcs8",format:"pem"})}function Ea(t){return Bi.createPrivateKey(t)}function Ta(t){let i=new Bi.X509Certificate(t),r=i.publicKey,n=[],e=i.subject.split(`
66
- `);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)n.push({shortName:s.trim(),value:l.trim()})}return{publicKey:r,subject:n}}async function Ke(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Jt.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=zl(i),e=[{shortName:"C",value:t.countryName||x.countryName},{shortName:"ST",value:t.stateName||x.stateName},{shortName:"L",value:t.localityName||x.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:s}=Ge({validityYears:t.validityYears||Jt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=Gl({serialNumber:qe(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:ql(r),notBefore:f,notAfter:s}}async function xe(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${Xr(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Ta(t.rootCA.certificate),r=Ea(t.rootCA.privateKey);E("ca",`Generating ${Jt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=Jt.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=zl(n),s=t.commonName||Ol(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||x.countryName},{shortName:"ST",value:t.stateName||x.stateName},{shortName:"L",value:t.localityName||x.localityName},{shortName:"O",value:t.organizationName||x.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=Ge({validityDays:t.validityDays||Jt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),o=Hl(t),u=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},$=t.extKeyUsage||{serverAuth:!0},{certificate:a}=Gl({serialNumber:qe(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:$,subjectAltName:o});return{certificate:a,privateKey:ql(e),notBefore:l,notAfter:h}}function Kl(t,i){E(T.STORAGE,`Storing certificate and private key with options: ${Xr(i)}`,i?.verbose);let{certPath:r,keyPath:n}=ze({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(T.STORAGE,`Certificate path: ${r}`,i?.verbose),E(T.STORAGE,`Private key path: ${n}`,i?.verbose);let e=Ne.dirname(r);if(!xt.existsSync(e))E(T.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),xt.mkdirSync(e,{recursive:!0});E(T.STORAGE,"Writing certificate file",i?.verbose),xt.writeFileSync(r,t.certificate);let f=Ne.dirname(n);if(!xt.existsSync(f))E(T.STORAGE,`Creating private key directory: ${f}`,i?.verbose),xt.mkdirSync(f,{recursive:!0});return E(T.STORAGE,"Writing private key file",i?.verbose),xt.writeFileSync(n,t.privateKey),E(T.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function xl(t,i){E(T.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=ze({basePath:i?.basePath,caCertPath:i?.caCertPath});E(T.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=Ne.dirname(r);if(!xt.existsSync(n))E(T.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),xt.mkdirSync(n,{recursive:!0});return E(T.STORAGE,"Writing CA certificate file",i?.verbose),xt.writeFileSync(r,t),E(T.STORAGE,"CA certificate stored successfully",i?.verbose),r}async function ga(t,i){if(br.platform()!=="darwin")return!1;try{let r=ps(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return E(T.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(ps("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(r))return E(T.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(T.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return E(T.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Sa={platform:"darwin",async addCertificate(t,i){if(await ga(t,i?.verbose)){E(T.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Si.success("Certificate is already trusted in system keychain");return}E(T.TRUST,"Adding certificate to macOS keychain",i?.verbose),await ii(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||x.commonName;E(T.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await ii(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),E(T.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw E(T.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Ca={platform:"win32",async addCertificate(t,i){E(T.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await ii(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||x.commonName;E(T.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await ii(`certutil -delstore -enterprise Root "${n}"`),E(T.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw E(T.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Ra={platform:"linux",async addCertificate(t,i){E(T.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=br.homedir(),n=Jt.LINUX_CERT_DB_FILENAME,e=Jt.LINUX_TRUST_ARGS;E(T.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=Fe(r,n);if(f.length===0){Si.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(T.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(T.TRUST,`Attempting to delete existing cert for ${x.commonName}`,i?.verbose),await ii(`certutil -d sql:${s} -D -n ${x.commonName}`)}catch(c){E(T.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(T.TRUST,`Adding new certificate to ${s}`,i?.verbose),await ii(`certutil -d sql:${s} -A -t ${e} -n ${x.commonName} -i ${t}`),Si.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||x.commonName;E(T.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=br.homedir(),f=Jt.LINUX_CERT_DB_FILENAME;E(T.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=Fe(e,f);if(s.length===0){Si.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(T.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await ii(`certutil -d sql:${c} -D -n "${n}"`),Si.info(`Cert removed from ${c}`)}catch(l){E(T.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},Ba={darwin:Sa,win32:Ca,linux:Ra};async function ke(t,i,r){E(T.TRUST,`Adding certificate to system trust store with options: ${Xr(r)}`,r?.verbose),E(T.TRUST,"Storing certificate and private key",r?.verbose);let n=Kl(t,r);E(T.TRUST,"Storing CA certificate",r?.verbose);let e=xl(i,r),f=br.platform();E(T.TRUST,`Detected platform: ${f}`,r?.verbose);let s=Ba[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(T.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await s.addCertificate(e,r),E(T.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as If}from"node:os";import{join as Of,resolve as ZA}from"node:path";import{existsSync as kl,statSync as Dl}from"fs";import{existsSync as Ua,mkdirSync as Xm,readdirSync as Qm,readFileSync as Fa,writeFileSync as td}from"fs";import{homedir as Ui}from"os";import{dirname as nd,resolve as Ct}from"path";import Yn from"process";import{existsSync as bl,statSync as Vl}from"fs";import{existsSync as af,mkdirSync as Ja,readdirSync as Na,writeFileSync as ja}from"fs";import{homedir as Fi}from"os";import{dirname as pl,resolve as at}from"path";import hi from"process";import{join as _a,relative as Wa,resolve as Pl}from"path";import Tn from"process";import{existsSync as Yc,mkdirSync as $d,readdirSync as yd,writeFileSync as wd}from"fs";import{homedir as De}from"os";import{dirname as Ad,resolve as ut}from"path";import Xi from"process";import{join as Ya,relative as Ia,resolve as vl}from"path";import gn from"process";import{existsSync as Ic,mkdirSync as Cd,readdirSync as Rd,writeFileSync as Bd}from"fs";import{dirname as Fd,resolve as Sn}from"path";import $f from"process";import{Buffer as ni}from"buffer";import{createCipheriv as Oa,createDecipheriv as Ha,randomBytes as be}from"crypto";import{closeSync as Ve,createReadStream as Xl,createWriteStream as La,existsSync as pe,fsyncSync as Ql,openSync as tc,writeFileSync as Za}from"fs";import{access as Ma,constants as ic,mkdir as za,readdir as Qr,rename as rc,stat as Ji,unlink as tn,writeFile as Pe}from"fs/promises";import{join as Ni}from"path";import ft from"process";import{pipeline as Ga}from"stream/promises";import{createGzip as nc}from"zlib";import ji from"process";import pt from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as qa,createDecipheriv as Ka,randomBytes as ve}from"crypto";import{closeSync as Xe,createReadStream as ec,createWriteStream as xa,existsSync as rn,fsyncSync as fc,openSync as sc,writeFileSync as ka}from"fs";import{access as Da,constants as lc,mkdir as ba,readdir as nn,rename as cc,stat as _i,unlink as en,writeFile as Qe}from"fs/promises";import{isAbsolute as Va,join as Wi,resolve as pa}from"path";import S from"process";import{pipeline as Pa}from"stream/promises";import{createGzip as hc}from"zlib";import Yi from"process";import Pt from"process";import fn from"process";import{existsSync as sn}from"fs";import{resolve as tf}from"path";import{existsSync as va}from"fs";import{existsSync as Xa,readdirSync as Qa}from"fs";import{extname as rf,resolve as oc}from"path";import t$ from"process";import{join as i$,relative as r$,resolve as uc}from"path";import Cn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as n$,createDecipheriv as e$,randomBytes as nf}from"crypto";import{closeSync as ef,createReadStream as ac,createWriteStream as f$,existsSync as ln,fsyncSync as $c,openSync as yc,writeFileSync as s$}from"fs";import{access as l$,constants as wc,mkdir as c$,readdir as cn,rename as mc,stat as Ii,unlink as hn,writeFile as ff}from"fs/promises";import{isAbsolute as h$,join as Oi,resolve as o$}from"path";import C from"process";import{pipeline as u$}from"stream/promises";import{createGzip as dc}from"zlib";import Hi from"process";import vt from"process";import un from"process";import{existsSync as an}from"fs";import{resolve as uf}from"path";import{existsSync as _y}from"fs";class _c{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!kl(t))return!0;return Dl(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=kl(r)?Dl(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Wc{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var En=new _c,Rf=new Wc;var a$=Object.defineProperty,$$=(t)=>t;function y$(t,i){this[t]=$$.bind(null,i)}var w$=(t,i)=>{for(var r in i)a$(t,r,{get:i[r],enumerable:!0,configurable:!0,set:y$.bind(i,r)})},m$=(t,i)=>()=>(t&&(i=t(t=0)),i),Oc={};w$(Oc,{withErrorRecovery:()=>Zc,tryLoadConfig:()=>M$,loadConfigWithResult:()=>L$,loadConfig:()=>Kc,isRetryableError:()=>_$,isConfigNotFoundError:()=>j$,isBunfigError:()=>Mc,globalPerformanceMonitor:()=>ir,globalCache:()=>Li,getEnvOrDefault:()=>W$,generateConfigTypes:()=>z$,defaultGeneratedDir:()=>vc,defaultConfigDir:()=>Pc,deepMergeWithArrayStrategy:()=>Nf,deepMerge:()=>zc,createLibraryConfig:()=>G$,config:()=>Z$,bunfigPlugin:()=>q$,applyEnvVarsToConfig:()=>vi,TypeGenerationError:()=>Tf,SchemaValidationError:()=>tr,PluginError:()=>Sf,PerformanceMonitor:()=>Uf,FileSystemError:()=>Ef,ErrorFactory:()=>ei,EnvVarError:()=>Nn,EnvProcessor:()=>In,ConfigValidator:()=>jf,ConfigValidationError:()=>df,ConfigNotFoundError:()=>Jn,ConfigMergeError:()=>Af,ConfigLoader:()=>_f,ConfigLoadError:()=>Qi,ConfigFileLoader:()=>On,ConfigCache:()=>Bf,CacheUtils:()=>kc,BunfigError:()=>Et,BrowserConfigError:()=>gf,ArrayMergeStrategies:()=>Vc});class Bf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!bl(t))return!0;return Vl(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=bl(r)?Vl(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Uf{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function d$(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function A$(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function E$(t){return t.getStats().size*2}function Ff(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((s)=>G(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((s)=>G(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Rn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=Ff(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let s of r[n])if(G(s)&&"name"in s){if(!f.find((l)=>G(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((l)=>G(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Rn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Rn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Rn(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Rn(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function T$(t,i){if(!Ic(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Ff(i,n)}catch{return null}}catch{return null}}async function g$({name:t="",cwd:i,defaultConfig:r}){let n=i||$f.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Sn(n,`${s}${c}`),h=await T$(l,r);if(h!==null)return h}try{let s=Sn(n,"package.json");if(Ic(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Ff(r,l)}catch{}}}catch{}return r}function S$(t,i={}){let r=gn.cwd();while(r.includes("storage"))r=vl(r,"..");let n=vl(r,t||"");if(i?.relative)return Ia(gn.cwd(),n);return n}async function C$(){try{let t=await g$({name:"clarity",defaultConfig:wn,cwd:gn.cwd(),endpoint:"",headers:{}});return{...wn,...t}}catch{return wn}}function K(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function R$(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class Hc{async format(t){let i=await R$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bn{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(t,i={}){this.name=t,this.config={...wf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Hc,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??ft.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...mn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...mn};return{...mn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:wf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Ma(this.config.logDirectory,ic.F_OK|ic.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await za(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ni.from(t);try{if(!pe(this.currentLogFile))await Pe(this.currentLogFile,"",{mode:420});if(e=tc(this.currentLogFile,"a",420),Za(e,l,{flag:"a"}),Ql(e),e!==void 0)Ve(e),e=void 0;if((await Ji(this.currentLogFile)).size===0){if(await Pe(this.currentLogFile,l,{flag:"w",mode:420}),(await Ji(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let o=h;if(o.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(o.code)){if(f<s-1){let u=typeof o.message==="string"?o.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(o?.code&&["ENOSPC","EDQUOT"].includes(o.code))throw Error(`Disk quota exceeded or no space left on device: ${o.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",o),o}finally{if(e!==void 0)try{Ve(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let o=l,u=typeof o.message==="string"?o.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((o)=>setTimeout(o,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ni(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(K())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return be(16).toString("hex")}generateKey(){return be(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=be(16),n=Oa("aes-256-gcm",i,r),e=ni.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ni.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=nc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ni.from(ni.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(K())return;let t=await Ji(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Qr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ji(r).catch(()=>null))try{if(await rc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await tn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Pe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ji(r).catch(()=>null))await rc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await Qr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await tn(Ni(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=Xl(t),n=La(i),e=nc();await Ga(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),pe(this.currentLogFile))try{let t=tc(this.currentLogFile,"r+");Ql(t),Ve(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!K()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Qr(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await tn(Ni(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?Z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=ft.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${Z.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!K()){let h=Dc[t],o=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:Z.gray(s),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:Z.green(s),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:h,tag:o,message:s,level:t}),console.error(u),c){let $=c.split(`
67
- `);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:Z.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!K()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
65
+ `}function Ke(){return Ui.randomBytes(20)}function Kl(t=2048){let{privateKey:i,publicKey:r}=Ui.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function ga(t){let i=t.export({type:"spki",format:"der"});return Ui.createHash("sha1").update(i).digest()}function xl(t){let i={serialNumber:t.serialNumber||Ke(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:ga(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let r=da(i),n=Ea(r,t.signingKey);return{certificate:Ta(n,"CERTIFICATE"),certificateDer:n}}function kl(t){return t.export({type:"pkcs8",format:"pem"})}function Sa(t){return Ui.createPrivateKey(t)}function Ca(t){let i=new Ui.X509Certificate(t),r=i.publicKey,n=[],e=i.subject.split(`
66
+ `);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)n.push({shortName:s.trim(),value:l.trim()})}return{publicKey:r,subject:n}}async function xe(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||Jt.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=Kl(i),e=[{shortName:"C",value:t.countryName||k.countryName},{shortName:"ST",value:t.stateName||k.stateName},{shortName:"L",value:t.localityName||k.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:s}=qe({validityYears:t.validityYears||Jt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=xl({serialNumber:Ke(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:kl(r),notBefore:f,notAfter:s}}async function ke(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${Xr(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Ca(t.rootCA.certificate),r=Sa(t.rootCA.privateKey);E("ca",`Generating ${Jt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=Jt.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=Kl(n),s=t.commonName||Zl(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||k.countryName},{shortName:"ST",value:t.stateName||k.stateName},{shortName:"L",value:t.localityName||k.localityName},{shortName:"O",value:t.organizationName||k.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=qe({validityDays:t.validityDays||Jt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),u=Ml(t),o=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},$=t.extKeyUsage||{serverAuth:!0},{certificate:a}=xl({serialNumber:Ke(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:o,extendedKeyUsage:$,subjectAltName:u});return{certificate:a,privateKey:kl(e),notBefore:l,notAfter:h}}function Dl(t,i){E(T.STORAGE,`Storing certificate and private key with options: ${Xr(i)}`,i?.verbose);let{certPath:r,keyPath:n}=Ge({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(T.STORAGE,`Certificate path: ${r}`,i?.verbose),E(T.STORAGE,`Private key path: ${n}`,i?.verbose);let e=je.dirname(r);if(!xt.existsSync(e))E(T.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),xt.mkdirSync(e,{recursive:!0});E(T.STORAGE,"Writing certificate file",i?.verbose),xt.writeFileSync(r,t.certificate);let f=je.dirname(n);if(!xt.existsSync(f))E(T.STORAGE,`Creating private key directory: ${f}`,i?.verbose),xt.mkdirSync(f,{recursive:!0});return E(T.STORAGE,"Writing private key file",i?.verbose),xt.writeFileSync(n,t.privateKey),E(T.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function bl(t,i){E(T.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=Ge({basePath:i?.basePath,caCertPath:i?.caCertPath});E(T.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=je.dirname(r);if(!xt.existsSync(n))E(T.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),xt.mkdirSync(n,{recursive:!0});return E(T.STORAGE,"Writing CA certificate file",i?.verbose),xt.writeFileSync(r,t),E(T.STORAGE,"CA certificate stored successfully",i?.verbose),r}async function Ra(t,i){if(br.platform()!=="darwin")return!1;try{let r=Xs(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return E(T.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Xs("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(r))return E(T.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(T.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return E(T.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Ba={platform:"darwin",async addCertificate(t,i){if(await Ra(t,i?.verbose)){E(T.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Ci.success("Certificate is already trusted in system keychain");return}E(T.TRUST,"Adding certificate to macOS keychain",i?.verbose),await ii(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||k.commonName;E(T.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await ii(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),E(T.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw E(T.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Ua={platform:"win32",async addCertificate(t,i){E(T.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await ii(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||k.commonName;E(T.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await ii(`certutil -delstore -enterprise Root "${n}"`),E(T.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw E(T.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Fa={platform:"linux",async addCertificate(t,i){E(T.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=br.homedir(),n=Jt.LINUX_CERT_DB_FILENAME,e=Jt.LINUX_TRUST_ARGS;E(T.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=Je(r,n);if(f.length===0){Ci.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(T.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(T.TRUST,`Attempting to delete existing cert for ${k.commonName}`,i?.verbose),await ii(`certutil -d sql:${s} -D -n ${k.commonName}`)}catch(c){E(T.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(T.TRUST,`Adding new certificate to ${s}`,i?.verbose),await ii(`certutil -d sql:${s} -A -t ${e} -n ${k.commonName} -i ${t}`),Ci.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||k.commonName;E(T.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=br.homedir(),f=Jt.LINUX_CERT_DB_FILENAME;E(T.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=Je(e,f);if(s.length===0){Ci.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(T.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await ii(`certutil -d sql:${c} -D -n "${n}"`),Ci.info(`Cert removed from ${c}`)}catch(l){E(T.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},Ja={darwin:Ba,win32:Ua,linux:Fa};async function De(t,i,r){E(T.TRUST,`Adding certificate to system trust store with options: ${Xr(r)}`,r?.verbose),E(T.TRUST,"Storing certificate and private key",r?.verbose);let n=Dl(t,r);E(T.TRUST,"Storing CA certificate",r?.verbose);let e=bl(i,r),f=br.platform();E(T.TRUST,`Detected platform: ${f}`,r?.verbose);let s=Ja[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(T.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await s.addCertificate(e,r),E(T.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as Of}from"node:os";import{join as Hf,resolve as Gd}from"node:path";import{existsSync as Vl,statSync as pl}from"fs";import{existsSync as Na,mkdirSync as iA,readdirSync as rA,readFileSync as ja,writeFileSync as nA}from"fs";import{homedir as Fi}from"os";import{dirname as sA,resolve as Ct}from"path";import Yn from"process";import{existsSync as Pl,statSync as vl}from"fs";import{existsSync as $f,mkdirSync as _a,readdirSync as Wa,writeFileSync as Ya}from"fs";import{homedir as Ji}from"os";import{dirname as Xl,resolve as at}from"path";import hi from"process";import{join as Ia,relative as Oa,resolve as Ql}from"path";import Tn from"process";import{existsSync as Hc,mkdirSync as mA,readdirSync as AA,writeFileSync as dA}from"fs";import{homedir as be}from"os";import{dirname as gA,resolve as ot}from"path";import Qi from"process";import{join as Ha,relative as La,resolve as tc}from"path";import gn from"process";import{existsSync as Lc,mkdirSync as UA,readdirSync as FA,writeFileSync as JA}from"fs";import{dirname as jA,resolve as Sn}from"path";import yf from"process";import{Buffer as ni}from"buffer";import{createCipheriv as Za,createDecipheriv as Ma,randomBytes as Ve}from"crypto";import{closeSync as pe,createReadStream as ic,createWriteStream as za,existsSync as Pe,fsyncSync as rc,openSync as nc,writeFileSync as Ga}from"fs";import{access as qa,constants as ec,mkdir as Ka,readdir as Qr,rename as fc,stat as Ni,unlink as tn,writeFile as ve}from"fs/promises";import{join as ji}from"path";import ft from"process";import{pipeline as xa}from"stream/promises";import{createGzip as sc}from"zlib";import _i from"process";import pt from"process";import{Buffer as Dt}from"buffer";import{createCipheriv as ka,createDecipheriv as Da,randomBytes as Xe}from"crypto";import{closeSync as Qe,createReadStream as lc,createWriteStream as ba,existsSync as rn,fsyncSync as cc,openSync as hc,writeFileSync as Va}from"fs";import{access as pa,constants as uc,mkdir as Pa,readdir as nn,rename as oc,stat as Wi,unlink as en,writeFile as tf}from"fs/promises";import{isAbsolute as va,join as Yi,resolve as Xa}from"path";import S from"process";import{pipeline as Qa}from"stream/promises";import{createGzip as ac}from"zlib";import Ii from"process";import Pt from"process";import fn from"process";import{existsSync as sn}from"fs";import{resolve as rf}from"path";import{existsSync as t$}from"fs";import{existsSync as i$,readdirSync as r$}from"fs";import{extname as nf,resolve as $c}from"path";import n$ from"process";import{join as e$,relative as f$,resolve as yc}from"path";import Cn from"process";import{Buffer as bt}from"buffer";import{createCipheriv as s$,createDecipheriv as l$,randomBytes as ef}from"crypto";import{closeSync as ff,createReadStream as wc,createWriteStream as c$,existsSync as ln,fsyncSync as mc,openSync as Ac,writeFileSync as h$}from"fs";import{access as u$,constants as dc,mkdir as o$,readdir as cn,rename as Ec,stat as Oi,unlink as hn,writeFile as sf}from"fs/promises";import{isAbsolute as a$,join as Hi,resolve as $$}from"path";import C from"process";import{pipeline as y$}from"stream/promises";import{createGzip as Tc}from"zlib";import Li from"process";import vt from"process";import on from"process";import{existsSync as an}from"fs";import{resolve as af}from"path";import{existsSync as Iy}from"fs";class Ic{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Vl(t))return!0;return pl(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Vl(r)?pl(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Oc{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var En=new Ic,Bf=new Oc;var w$=Object.defineProperty,m$=(t)=>t;function A$(t,i){this[t]=m$.bind(null,i)}var d$=(t,i)=>{for(var r in i)w$(t,r,{get:i[r],enumerable:!0,configurable:!0,set:A$.bind(i,r)})},E$=(t,i)=>()=>(t&&(i=t(t=0)),i),Zc={};d$(Zc,{withErrorRecovery:()=>Gc,tryLoadConfig:()=>q$,loadConfigWithResult:()=>z$,loadConfig:()=>Dc,isRetryableError:()=>I$,isConfigNotFoundError:()=>Y$,isBunfigError:()=>qc,globalPerformanceMonitor:()=>rr,globalCache:()=>Zi,getEnvOrDefault:()=>O$,generateConfigTypes:()=>K$,defaultGeneratedDir:()=>th,defaultConfigDir:()=>Qc,deepMergeWithArrayStrategy:()=>jf,deepMerge:()=>Kc,createLibraryConfig:()=>x$,config:()=>G$,bunfigPlugin:()=>k$,applyEnvVarsToConfig:()=>Xi,TypeGenerationError:()=>gf,SchemaValidationError:()=>ir,PluginError:()=>Cf,PerformanceMonitor:()=>Ff,FileSystemError:()=>Tf,ErrorFactory:()=>ei,EnvVarError:()=>Nn,EnvProcessor:()=>In,ConfigValidator:()=>_f,ConfigValidationError:()=>df,ConfigNotFoundError:()=>Jn,ConfigMergeError:()=>Ef,ConfigLoader:()=>Wf,ConfigLoadError:()=>tr,ConfigFileLoader:()=>On,ConfigCache:()=>Uf,CacheUtils:()=>Vc,BunfigError:()=>Et,BrowserConfigError:()=>Sf,ArrayMergeStrategies:()=>vc});class Uf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Pl(t))return!0;return vl(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Pl(r)?vl(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Ff{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function T$(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function g$(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function S$(t){return t.getStats().size*2}function Jf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&q(i[0])&&"id"in i[0]&&i[0].id===3&&q(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(q(i)&&q(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(q(t)&&"arr"in t&&Array.isArray(t.arr)&&q(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&q(i[0])&&q(t[0])){let n=[...i];for(let e of t)if(q(e)&&"name"in e){if(!n.find((s)=>q(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(q(e)&&"path"in e){if(!n.find((s)=>q(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Rn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!q(i)||!q(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(q(e)&&q(r[n]))r[n]=Jf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&q(e[0])&&q(r[n][0])){let f=[...e];for(let s of r[n])if(q(s)&&"name"in s){if(!f.find((l)=>q(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(q(s)&&"path"in s){if(!f.find((l)=>q(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Rn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Rn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Rn(t[r],i[r]))return!1;return!0}if(q(t)&&q(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Rn(t[e],i[e]))return!1}return!0}return!1}function q(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function C$(t,i){if(!Lc(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Jf(i,n)}catch{return null}}catch{return null}}async function R$({name:t="",cwd:i,defaultConfig:r}){let n=i||yf.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Sn(n,`${s}${c}`),h=await C$(l,r);if(h!==null)return h}try{let s=Sn(n,"package.json");if(Lc(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Jf(r,l)}catch{}}}catch{}return r}function B$(t,i={}){let r=gn.cwd();while(r.includes("storage"))r=tc(r,"..");let n=tc(r,t||"");if(i?.relative)return La(gn.cwd(),n);return n}async function U$(){try{let t=await R$({name:"clarity",defaultConfig:wn,cwd:gn.cwd(),endpoint:"",headers:{}});return{...wn,...t}}catch{return wn}}function x(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function F$(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class Mc{async format(t){let i=await F$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:_i.pid,hostname:i(),environment:_i.env.NODE_ENV||"development",platform:_i.platform,version:_i.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_i.env.NODE_ENV||_i.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bn{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(t,i={}){this.name=t,this.config={...mf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Mc,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??ft.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...mn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...mn};return{...mn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:mf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await qa(this.config.logDirectory,ec.F_OK|ec.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Ka(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ni.from(t);try{if(!Pe(this.currentLogFile))await ve(this.currentLogFile,"",{mode:420});if(e=nc(this.currentLogFile,"a",420),Ga(e,l,{flag:"a"}),rc(e),e!==void 0)pe(e),e=void 0;if((await Ni(this.currentLogFile)).size===0){if(await ve(this.currentLogFile,l,{flag:"w",mode:420}),(await Ni(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let o=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{pe(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,o=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,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 ji(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 ji(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ji(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(x())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ve(16).toString("hex")}generateKey(){return Ve(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ve(16),n=Za("aes-256-gcm",i,r),e=ni.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ni.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=sc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ni.from(ni.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(x())return;let t=await Ni(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Qr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ni(r).catch(()=>null))try{if(await fc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await tn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ve(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ni(r).catch(()=>null))await fc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await Qr(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await tn(ji(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=ic(t),n=za(i),e=sc();await xa(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Pe(this.currentLogFile))try{let t=nc(this.currentLogFile,"r+");rc(t),pe(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!x()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Qr(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await tn(ji(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=ft.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${z.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!x()){let h=pc[t],u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:z.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:z.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:s,level:t}),console.error(o),c){let $=c.split(`
67
+ `);for(let a of $)if(a.trim()&&!a.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:z.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!x()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
68
68
  `;if(c)l+=`${c}
69
- `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!K()){let r=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:Z.blue("◐"),tag:r,message:`${Z.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
70
- `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!K()){let o=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:Z.green("✓"),tag:o,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!K())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Bn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(K())throw Error("createReadStream is not supported in browser environments");if(!pe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xl(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ni.isBuffer(t)?t:ni.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=Ha("aes-256-gcm",r,e);return c.setAuthTag(f),ni.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return K()}isServerMode(){return!K()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!K()){let f=t.split(`
71
- `),s=Math.max(...f.map((o)=>o.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((o)=>{let u=" ".repeat(s-o.length-2);return`│ ${o}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:Z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(c)})),h.forEach((o)=>console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(o),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:Z.cyan(l),showTimestamp:!1}))}else if(!K())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
72
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(K())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${Z.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();ft.stdin.removeListener("data",r);try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!1)}catch{}ft.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!0)}catch{}ft.stdin.resume(),ft.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let o=i[c++];switch(h){case"s":return String(o);case"d":case"i":return Number(o).toString();case"j":case"o":return JSON.stringify(o,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!K()){let s=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",c=Z.blue("◐");console.error(`${c} ${s} ${Z.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
73
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||K()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||K())return;ft.stdout.write(`${"\r".padEnd(ft.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||K()||!ft.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=Z.green("━".repeat(n)),s=Z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=i||r===100?Z.green("✓"):Z.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${Z.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=ft.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,ft.stdout.write(t.lastRenderedLine),i)ft.stdout.write(`
74
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||K()||!ft.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(K()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Qr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Ni(this.config.logDirectory,n);if(t.before)try{if((await Ji(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await tn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function yn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&Y(i[0])&&"id"in i[0]&&i[0].id===3&&Y(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(Y(i)&&Y(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(Y(t)&&"arr"in t&&Array.isArray(t.arr)&&Y(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&Y(i[0])&&Y(t[0])){let n=[...i];for(let e of t)if(Y(e)&&"name"in e){if(!n.find((s)=>Y(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(Y(e)&&"path"in e){if(!n.find((s)=>Y(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Un(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!Y(i)||!Y(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(Y(e)&&Y(r[n]))r[n]=yn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&Y(e[0])&&Y(r[n][0])){let f=[...e];for(let s of r[n])if(Y(s)&&"name"in s){if(!f.find((l)=>Y(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(Y(s)&&"path"in s){if(!f.find((l)=>Y(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Un(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Jf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:yn(t,i);if(Array.isArray(t))return r==="replace"?i:yn(t,i);if(!Y(i)||!Y(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=yn(s,f);else if(Y(f)&&Y(s))n[e]=Jf(s,f,r);else n[e]=f}return n}function Un(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Un(t[r],i[r]))return!1;return!0}if(Y(t)&&Y(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Un(t[e],i[e]))return!1}return!0}return!1}function Y(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function on(t,i,r="replace"){if(!Yc(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Jf(i,e,r)}catch{return null}}catch{return null}}function B$(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${u.map($).join("_")}`,m=`${n}_${u.map((y)=>y.toUpperCase()).join("_")}`;if(r)lt.info(`Checking environment variable ${a} for config ${t}.${u.join(".")}`);if(typeof o==="object"&&o!==null&&!Array.isArray(o))l[h]=f(o,u);else{let y=Xi.env[a]||Xi.env[m];if(y!==void 0){if(r)lt.info(`Using environment variable ${y?a:m} for config ${t}.${u.join(".")}`);if(typeof o==="number")l[h]=Number(y);else if(typeof o==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(o))try{let d=JSON.parse(y);if(Array.isArray(d))l[h]=d;else l[h]=y.split(",").map((A)=>A.trim())}catch{l[h]=y.split(",").map((d)=>d.trim())}else l[h]=y}}}return l}return f(e)}async function U$({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?B$(t,e,f):e,h=r||Xi.cwd(),o=[".ts",".js",".mjs",".cjs",".json"];if(f)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let u=[t,`.${t}`].filter(Boolean),$=[`${t}.config`,`.${t}.config`].filter(Boolean),a=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([h,ut(h,"config"),ut(h,".config"),n?ut(h,n):void 0].filter(Boolean)));for(let d of y){if(f)lt.info(`Searching for configuration in: ${d}`);let g=[ut(h,"config"),ut(h,".config")].concat(n?[ut(h,n)]:[]).includes(d)?[...u,...$,...a,...m]:[...$,...u,...m,...a];for(let I of g)for(let O of o){let H=ut(d,`${I}${O}`),qi=await on(H,l,c);if(qi!==null){if(f)lt.success(`Configuration loaded from: ${H}`);return qi}}}if(t){let d=ut(De(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)lt.info(`Checking user config directory: ${d}`);for(let g of A)for(let I of o){let O=ut(d,`${g}${I}`),H=await on(O,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory: ${O}`);return H}}}if(t){let d=ut(De(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)lt.info(`Checking user config directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ut(d,`${g}${I}`),H=await on(O,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory dotfile: ${O}`);return H}}}if(t){let d=De(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)lt.info(`Checking user home directory for dotfile configs: ${d}`);for(let g of A)for(let I of o){let O=ut(d,`${g}${I}`),H=await on(O,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user home directory: ${O}`);return H}}}try{let d=ut(h,"package.json");if(Yc(d)){let A=await import(d),g=A[t];if(!g&&i){if(g=A[i],g&&f)lt.success(`Using alias "${i}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(f)lt.success(`Configuration loaded from package.json: ${g===A[t]?t:i}`);return Jf(l,g,c)}catch(I){if(f)lt.warn("Failed to merge package.json config:",I)}}}catch(d){if(f)lt.warn("Failed to load package.json:",d)}if(f)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function F$(t,i={}){let r=Tn.cwd();while(r.includes("storage"))r=Pl(r,"..");let n=Pl(r,t||"");if(i?.relative)return Wa(Tn.cwd(),n);return n}async function J$(){try{let t=await U$({name:"clarity",alias:"logging",defaultConfig:dn,cwd:Tn.cwd()});return{...dn,...t||{}}}catch{return dn}}function P(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function N$(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pt<"u"){let t=Pt.type;if(t==="renderer"||t==="worker")return!1;return!!(Pt.versions&&(Pt.versions.node||Pt.versions.bun))}return!1}class Lc{async format(t){let i=await N$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Yi.pid,hostname:i(),environment:Yi.env.NODE_ENV||"development",platform:Yi.platform,version:Yi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yi.env.NODE_ENV||Yi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Fn{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(t,i={}){this.name=t,this.config={...mf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Lc,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...An,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...An};return{...An,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:mf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Da(this.config.logDirectory,lc.F_OK|lc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await ba(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Dt.from(t);try{if(!rn(this.currentLogFile))await Qe(this.currentLogFile,"",{mode:420});if(e=sc(this.currentLogFile,"a",420),ka(e,l,{flag:"a"}),fc(e),e!==void 0)Xe(e),e=void 0;if((await _i(this.currentLogFile)).size===0){if(await Qe(this.currentLogFile,l,{flag:"w",mode:420}),(await _i(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let o=h;if(o.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(o.code)){if(f<s-1){let u=typeof o.message==="string"?o.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(o?.code&&["ENOSPC","EDQUOT"].includes(o.code))throw Error(`Disk quota exceeded or no space left on device: ${o.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",o),o}finally{if(e!==void 0)try{Xe(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let o=l,u=typeof o.message==="string"?o.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((o)=>setTimeout(o,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Wi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Wi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Wi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ve(16).toString("hex")}generateKey(){return ve(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=ve(16),n=qa("aes-256-gcm",i,r),e=Dt.isBuffer(t)?t:Dt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Dt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=hc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Dt.from(Dt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await _i(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await nn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await _i(r).catch(()=>null))try{if(await cc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await en(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Qe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await _i(r).catch(()=>null))await cc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await nn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await en(Wi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=ec(t),n=xa(i),e=hc();await Pa(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),rn(this.currentLogFile))try{let t=sc(this.currentLogFile,"r+");fc(t),Xe(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await nn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await en(Wi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?B.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof S.env.NO_COLOR<"u",i=S.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=S.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${B.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=B.underline(B.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>B.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>B.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>B.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>B.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>B.strikethrough(n)),i}supportsHyperlinks(){if(P())return!1;let t=S.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=S.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Va(i)||i.startsWith("./")||i.startsWith("../"))i=pa(i);else return null;return rn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":bc[t],$=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:B.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:B.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
75
- `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:B.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
76
- `;if(c)o+=`${c}
77
- `;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!P()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!P()&&S.stdout.isTTY)S.stdout.write(`
69
+ `;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!x()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:z.blue("◐"),tag:r,message:`${z.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
70
+ `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!x()){let u=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:z.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!x())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Bn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(x())throw Error("createReadStream is not supported in browser environments");if(!Pe(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ic(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ni.isBuffer(t)?t:ni.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=Ma("aes-256-gcm",r,e);return c.setAuthTag(f),ni.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return x()}isServerMode(){return!x()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!x()){let f=t.split(`
71
+ `),s=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((u)=>{let o=" ".repeat(s-u.length-2);return`│ ${u}${o} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(l),showTimestamp:!1}))}else if(!x())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
72
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(x())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${z.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();ft.stdin.removeListener("data",r);try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!1)}catch{}ft.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof ft.stdin.setRawMode==="function")ft.stdin.setRawMode(!0)}catch{}ft.stdin.resume(),ft.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!x()){let s=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=z.blue("◐");console.error(`${c} ${s} ${z.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
73
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||x()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||x())return;ft.stdout.write(`${"\r".padEnd(ft.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||x()||!ft.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=z.green("━".repeat(n)),s=z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||r===100?z.green("✓"):z.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=ft.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,ft.stdout.write(t.lastRenderedLine),i)ft.stdout.write(`
74
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||x()||!ft.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(x()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Qr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=ji(this.config.logDirectory,n);if(t.before)try{if((await Ni(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await tn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function yn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&I(i[0])&&"id"in i[0]&&i[0].id===3&&I(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(I(i)&&I(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(I(t)&&"arr"in t&&Array.isArray(t.arr)&&I(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&I(i[0])&&I(t[0])){let n=[...i];for(let e of t)if(I(e)&&"name"in e){if(!n.find((s)=>I(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(I(e)&&"path"in e){if(!n.find((s)=>I(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Un(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!I(i)||!I(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(I(e)&&I(r[n]))r[n]=yn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&I(e[0])&&I(r[n][0])){let f=[...e];for(let s of r[n])if(I(s)&&"name"in s){if(!f.find((l)=>I(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(I(s)&&"path"in s){if(!f.find((l)=>I(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Un(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Nf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:yn(t,i);if(Array.isArray(t))return r==="replace"?i:yn(t,i);if(!I(i)||!I(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=yn(s,f);else if(I(f)&&I(s))n[e]=Nf(s,f,r);else n[e]=f}return n}function Un(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Un(t[r],i[r]))return!1;return!0}if(I(t)&&I(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Un(t[e],i[e]))return!1}return!0}return!1}function I(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function un(t,i,r="replace"){if(!Hc(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Nf(i,e,r)}catch{return null}}catch{return null}}function J$(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=(y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase(),a=`${n}_${o.map($).join("_")}`,m=`${n}_${o.map((y)=>y.toUpperCase()).join("_")}`;if(r)lt.info(`Checking environment variable ${a} for config ${t}.${o.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))l[h]=f(u,o);else{let y=Qi.env[a]||Qi.env[m];if(y!==void 0){if(r)lt.info(`Using environment variable ${y?a:m} for config ${t}.${o.join(".")}`);if(typeof u==="number")l[h]=Number(y);else if(typeof u==="boolean")l[h]=y.toLowerCase()==="true";else if(Array.isArray(u))try{let A=JSON.parse(y);if(Array.isArray(A))l[h]=A;else l[h]=y.split(",").map((d)=>d.trim())}catch{l[h]=y.split(",").map((A)=>A.trim())}else l[h]=y}}}return l}return f(e)}async function N$({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?J$(t,e,f):e,h=r||Qi.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)lt.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[t,`.${t}`].filter(Boolean),$=[`${t}.config`,`.${t}.config`].filter(Boolean),a=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],y=Array.from(new Set([h,ot(h,"config"),ot(h,".config"),n?ot(h,n):void 0].filter(Boolean)));for(let A of y){if(f)lt.info(`Searching for configuration in: ${A}`);let g=[ot(h,"config"),ot(h,".config")].concat(n?[ot(h,n)]:[]).includes(A)?[...o,...$,...a,...m]:[...$,...o,...m,...a];for(let O of g)for(let L of u){let H=ot(A,`${O}${L}`),oi=await un(H,l,c);if(oi!==null){if(f)lt.success(`Configuration loaded from: ${H}`);return oi}}}if(t){let A=ot(be(),".config",t),d=["config",`${t}.config`];if(i)d.push(`${i}.config`);if(f)lt.info(`Checking user config directory: ${A}`);for(let g of d)for(let O of u){let L=ot(A,`${g}${O}`),H=await un(L,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory: ${L}`);return H}}}if(t){let A=ot(be(),".config"),d=[`.${t}.config`];if(i)d.push(`.${i}.config`);if(f)lt.info(`Checking user config directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ot(A,`${g}${O}`),H=await un(L,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user config directory dotfile: ${L}`);return H}}}if(t){let A=be(),d=[`.${t}.config`,`.${t}`];if(i)d.push(`.${i}.config`),d.push(`.${i}`);if(f)lt.info(`Checking user home directory for dotfile configs: ${A}`);for(let g of d)for(let O of u){let L=ot(A,`${g}${O}`),H=await un(L,l,c);if(H!==null){if(f)lt.success(`Configuration loaded from user home directory: ${L}`);return H}}}try{let A=ot(h,"package.json");if(Hc(A)){let d=await import(A),g=d[t];if(!g&&i){if(g=d[i],g&&f)lt.success(`Using alias "${i}" configuration from package.json`)}if(g&&typeof g==="object"&&!Array.isArray(g))try{if(f)lt.success(`Configuration loaded from package.json: ${g===d[t]?t:i}`);return Nf(l,g,c)}catch(O){if(f)lt.warn("Failed to merge package.json config:",O)}}}catch(A){if(f)lt.warn("Failed to load package.json:",A)}if(f)lt.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function j$(t,i={}){let r=Tn.cwd();while(r.includes("storage"))r=Ql(r,"..");let n=Ql(r,t||"");if(i?.relative)return Oa(Tn.cwd(),n);return n}async function _$(){try{let t=await N$({name:"clarity",alias:"logging",defaultConfig:An,cwd:Tn.cwd()});return{...An,...t||{}}}catch{return An}}function P(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function W$(){if(Pt.env.NODE_ENV==="test"||Pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pt<"u"){let t=Pt.type;if(t==="renderer"||t==="worker")return!1;return!!(Pt.versions&&(Pt.versions.node||Pt.versions.bun))}return!1}class zc{async format(t){let i=await W$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ii.pid,hostname:i(),environment:Ii.env.NODE_ENV||"development",platform:Ii.platform,version:Ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ii.env.NODE_ENV||Ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Fn{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(t,i={}){this.name=t,this.config={...Af},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new zc,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??S.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...dn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...dn};return{...dn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Af.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await pa(this.config.logDirectory,uc.F_OK|uc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Pa(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Dt.from(t);try{if(!rn(this.currentLogFile))await tf(this.currentLogFile,"",{mode:420});if(e=hc(this.currentLogFile,"a",420),Va(e,l,{flag:"a"}),cc(e),e!==void 0)Qe(e),e=void 0;if((await Wi(this.currentLogFile)).size===0){if(await tf(this.currentLogFile,l,{flag:"w",mode:420}),(await Wi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let o=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{Qe(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,o=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,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 Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Xe(16).toString("hex")}generateKey(){return Xe(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Xe(16),n=ka("aes-256-gcm",i,r),e=Dt.isBuffer(t)?t:Dt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Dt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ac(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Dt.from(Dt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Wi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await nn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Wi(r).catch(()=>null))try{if(await oc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await en(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await tf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Wi(r).catch(()=>null))await oc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await nn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await en(Yi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=lc(t),n=ba(i),e=ac();await Qa(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),rn(this.currentLogFile))try{let t=hc(this.currentLogFile,"r+");cc(t),Qe(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await nn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await en(Yi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?B.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof S.env.NO_COLOR<"u",i=S.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof S.stderr<"u"&&S.stderr.isTTY||typeof S.stdout<"u"&&S.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=S.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${B.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=B.underline(B.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>B.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>B.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>B.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>B.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>B.strikethrough(n)),i}supportsHyperlinks(){if(P())return!1;let t=S.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=S.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(va(i)||i.startsWith("./")||i.startsWith("../"))i=Xa(i);else return null;return rn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":Pc[t],$=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:B.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:B.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
75
+ `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:B.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
76
+ `;if(c)u+=`${c}
77
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!P()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!P()&&S.stdout.isTTY)S.stdout.write(`
78
78
  `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&S.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":B.blue("◐"),tag:r,message:`${B.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
79
- `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":B.green("✓"),tag:o,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Fn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!rn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ec(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Dt.isBuffer(t)?t:Dt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Ka("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=Dt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
80
- `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:B.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(o),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
81
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${B.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();S.stdin.removeListener("data",r);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(o,u)=>{if(u==="%")return"%";if(h>=i.length)return o;let $=i[h++];switch(u){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return o}}),h<i.length)r+=` ${i.slice(h).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${B.blue("◐")} `;console.error(`${h}${l} ${B.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
82
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!S.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=B.green("━".repeat(n)),s=B.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?B.green("✓"):B.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=S.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,S.stdout.write(t.lastRenderedLine),i)S.stdout.write(`
83
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!S.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await nn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Wi(this.config.logDirectory,n);if(t.before)try{if((await _i(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await en(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Zc(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Mc(t){return t instanceof Et}function j$(t){return t instanceof Jn}function _$(t){if(Mc(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>t.message.toLowerCase().includes(r.toLowerCase()))}class In{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return ir.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=fn.env[l]||(h?fn.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=fn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof Nn)throw u;throw ei.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ei.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(fn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
79
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":B.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Fn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!rn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return lc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Dt.isBuffer(t)?t:Dt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Da("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=Dt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
80
+ `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:B.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(u),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
81
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${B.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();S.stdin.removeListener("data",r);try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!1)}catch{}S.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof S.stdin.setRawMode==="function")S.stdin.setRawMode(!0)}catch{}S.stdin.resume(),S.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(u,o)=>{if(o==="%")return"%";if(h>=i.length)return u;let $=i[h++];switch(o){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return u}}),h<i.length)r+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${B.blue("◐")} `;console.error(`${h}${l} ${B.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
82
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!S.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=B.green("━".repeat(n)),s=B.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?B.green("✓"):B.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=S.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,S.stdout.write(t.lastRenderedLine),i)S.stdout.write(`
83
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!S.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await nn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Yi(this.config.logDirectory,n);if(t.before)try{if((await Wi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await en(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Gc(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function qc(t){return t instanceof Et}function Y$(t){return t instanceof Jn}function I$(t){if(qc(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>t.message.toLowerCase().includes(r.toLowerCase()))}class In{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return rr.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=fn.env[l]||(h?fn.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=fn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof Nn)throw o;throw ei.envVar(l,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ei.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(fn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
84
84
 
85
85
  `;for(let n of t)r+=`${n.key}
86
86
  `,r+=` Type: ${n.type}
@@ -92,25 +92,25 @@ ${n.join(`
92
92
  `;r+=`| Variable | Type | Description | Example |
93
93
  `,r+=`|----------|------|-------------|----------|
94
94
  `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
95
- `;return r}}function W$(t,i){let r=xc("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function zc(t,i,r={}){return Gc(t,i,r,new WeakMap)}function Gc(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return qc(t,i,e,n);if(!Rt(i)||!Rt(t))return i;return H$(t,i,r,n)}function qc(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Y$(t,i);case"smart":return I$(t,i,n);default:return i}return i}function Y$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>yf(e,n)))r.push(n);return r}function I$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Rt(i[0])&&Rt(t[0]))return O$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function O$(t,i,r){let n=[...i];for(let e of t){if(!Rt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Rt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function H$(t,i,r,n){let e=i;if(Rt(e)&&n.has(e))return n.get(e);let f={...t};if(Rt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Rt(c)&&Rt(l))f[s]=Gc(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=qc(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Nf(t,i,r="replace"){return zc(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function yf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!yf(t[r],i[r]))return!1;return!0}if(Rt(t)&&Rt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!yf(t[e],i[e]))return!1}return!0}return!1}function Rt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class On{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Li.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!sn(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new Qi(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Qi(t,Error("Configuration must export a valid object"),"unknown");let d={config:Nf(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Li.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?ei.configLoad(t,h):ei.configLoad(t,Error(String(h)))}};if(s)return ir.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(tf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Zc(async()=>{return sn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!sn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=tf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=tf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!sn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class jf{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await ir.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!va(i))throw new tr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new tr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:pc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class _f{fileLoader=new On;envProcessor=new In;validator=new jf;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw _t.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||hi.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(at(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw ei.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?vi(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)_t.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)_t.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?vi(t,r,e):r,c=[at(Fi(),".config",t),at(Fi(),".config"),Fi()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)_t.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?vi(t,n,f):n;try{let l=at(r,"package.json");if(!af(l))return null;let h=await import(l),o=h[t],u=t;if(!o&&i)o=h[i],u=i;if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)_t.success(`Configuration loaded from package.json: ${u}`);return{config:Nf(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:vi(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ei.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Li.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Li.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(Fi(),".config",t),at(Fi(),".config"),Fi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function Ac(t){let r=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return r||n}async function L$(t){return Xt.loadConfig({...t,__strictErrorHandling:!0})}async function Kc(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await Xt.loadConfig(t);else n=await Xt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)_t.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Xt.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function Z$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await Xt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Ac(r)))return(await Xt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await Xt.loadConfig({...t,cwd:t.cwd||hi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Ac(i)))return(await Xt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function M$(t,i,r="replace"){let n=new On;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function vi(t,i,r=!1){let n=new In,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=hi.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}function z$(t){let i=at(hi.cwd(),t.configDir),r=at(hi.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!af(pl(n)))Ja(pl(n),{recursive:!0,mode:511});let e=af(i)?Na(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${wy}
95
+ `;return r}}function O$(t,i){let r=bc("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function Kc(t,i,r={}){return xc(t,i,r,new WeakMap)}function xc(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return kc(t,i,e,n);if(!Rt(i)||!Rt(t))return i;return M$(t,i,r,n)}function kc(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return H$(t,i);case"smart":return L$(t,i,n);default:return i}return i}function H$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>wf(e,n)))r.push(n);return r}function L$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Rt(i[0])&&Rt(t[0]))return Z$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Z$(t,i,r){let n=[...i];for(let e of t){if(!Rt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Rt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function M$(t,i,r,n){let e=i;if(Rt(e)&&n.has(e))return n.get(e);let f={...t};if(Rt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Rt(c)&&Rt(l))f[s]=xc(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=kc(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function jf(t,i,r="replace"){return Kc(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function wf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!wf(t[r],i[r]))return!1;return!0}if(Rt(t)&&Rt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!wf(t[e],i[e]))return!1}return!0}return!1}function Rt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class On{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Zi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!sn(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new tr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new tr(t,Error("Configuration must export a valid object"),"unknown");let A={config:jf(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Zi.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?ei.configLoad(t,h):ei.configLoad(t,Error(String(h)))}};if(s)return rr.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(rf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Gc(async()=>{return sn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!sn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=rf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=rf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!sn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class _f{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let u=[],o=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await rr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!t$(i))throw new ir(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new ir(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:Xc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Wf{fileLoader=new On;envProcessor=new In;validator=new _f;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||u))throw l;if(o&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw _t.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,o=f||hi.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(at(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw ei.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Xi(t,e,s):e,u=this.getLocalDirectories(r,n);for(let o of u){if(s)_t.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)_t.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Xi(t,r,e):r,c=[at(Ji(),".config",t),at(Ji(),".config"),Ji()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)_t.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Xi(t,n,f):n;try{let l=at(r,"package.json");if(!$f(l))return null;let h=await import(l),u=h[t],o=t;if(!u&&i)u=h[i],o=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)_t.success(`Configuration loaded from package.json: ${o}`);return{config:jf(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xi(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ei.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Zi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Zi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(Ji(),".config",t),at(Ji(),".config"),Ji()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function gc(t){let r=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return r||n}async function z$(t){return Xt.loadConfig({...t,__strictErrorHandling:!0})}async function Dc(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await Xt.loadConfig(t);else n=await Xt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)_t.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await Xt.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function G$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await Xt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&gc(r)))return(await Xt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await Xt.loadConfig({...t,cwd:t.cwd||hi.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&gc(i)))return(await Xt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function q$(t,i,r="replace"){let n=new On;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function Xi(t,i,r=!1){let n=new In,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=hi.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}function K$(t){let i=at(hi.cwd(),t.configDir),r=at(hi.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!$f(Xl(n)))_a(Xl(n),{recursive:!0,mode:511});let e=$f(i)?Wa(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${dy}
96
96
  export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
97
- `;ja(n,f,{mode:438})}function G$(t){let i=null,r=null,n=()=>{if(!r)r=Kc(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)_t.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function q$(t){let i=oc(t$.cwd(),t?.configDir||"./config");function r(){if(!Xa(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Qa(i).filter((l)=>e.has(rf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let o=rf(h).toLowerCase(),u=c.get(l);if(!u){c.set(l,h);continue}let $=rf(u).toLowerCase();if(f.indexOf(o)<f.indexOf($))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((h)=>h.base),s=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
98
- ${e.map((h)=>{let o=oc(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${o}').default`}).join(`,
97
+ `;Ya(n,f,{mode:438})}function x$(t){let i=null,r=null,n=()=>{if(!r)r=Dc(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)_t.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function k$(t){let i=$c(n$.cwd(),t?.configDir||"./config");function r(){if(!i$(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=r$(i).filter((l)=>e.has(nf(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let u=nf(h).toLowerCase(),o=c.get(l);if(!o){c.set(l,h);continue}let $=nf(o).toLowerCase();if(f.indexOf(u)<f.indexOf($))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((h)=>h.base),s=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
98
+ ${e.map((h)=>{let u=$c(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${u}').default`}).join(`,
99
99
  `)}
100
100
  }`:"Record<string, any>";return`export type ConfigNames = ${s}
101
101
  export type ConfigByName = ${c}
102
102
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
103
103
  export type ConfigOf = Config
104
- `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var xc,Li,ir,kc,K$,x$,Ec,wn,wf,st,Z,k$,Tc,D$,gc,b$,V$,sf,p$,Sc,Cc,lf,P$,v$,X$,Q$,mn,Dc,ty,lt,iy,ry,Rc,dn,mf,v,B,ny,Bc,ey,Uc,fy,sy,cf,ly,Fc,Jc,cy,hf,hy,oy,uy,ay,$y,An,bc,yy,wy="0.15.6",Et,Jn,Qi,df,Af,Nn,Ef,Tf,tr,gf,Sf,ei,Vc,pc,_t,Xt,Pc,vc,my=m$(async()=>{xc=import.meta.require,Li=new Bf,ir=new Uf,kc={createKey:d$,isEquivalent:A$,estimateMemoryUsage:E$},K$=Sn($f.cwd(),"config"),x$=Sn($f.cwd(),"src/generated"),Ec=gn.env.CLARITY_LOG_DIR||Ya(S$(),"logs"),wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ec,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},wf=await C$(),st={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},Z=st,k$=st.red,Tc=st.green,D$=st.yellow,gc=st.blue,b$=st.magenta,V$=st.cyan,sf=st.white,p$=st.gray,Sc=st.bgRed,Cc=st.bgYellow,lf=st.bold,P$=st.dim,v$=st.italic,X$=st.underline,Q$=st.reset,mn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Dc={debug:"\uD83D\uDD0D",info:gc("ℹ"),success:Tc("✓"),warning:Cc(sf(lf(" WARN "))),error:Sc(sf(lf(" ERROR ")))},ty=new Bn("stacks"),lt=new Bn("bunfig",{showTags:!0}),iy=ut(Xi.cwd(),"config"),ry=ut(Xi.cwd(),"src/generated"),Rc=Tn.env.CLARITY_LOG_DIR||_a(F$(),"logs"),dn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mf=await J$(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},B=v,ny=v.red,Bc=v.green,ey=v.yellow,Uc=v.blue,fy=v.magenta,sy=v.cyan,cf=v.white,ly=v.gray,Fc=v.bgRed,Jc=v.bgYellow,cy=v.bgGray,hf=v.bold,hy=v.dim,oy=v.italic,uy=v.underline,ay=v.strikethrough,$y=v.reset,An={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bc={debug:"\uD83D\uDD0D",info:Uc("ℹ"),success:Bc("✓"),warning:Jc(cf(hf(" WARN "))),error:Fc(cf(hf(" ERROR ")))},yy=new Fn("stacks"),Et=class extends Error{timestamp;context;constructor(i,r={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Jn=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},Qi=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},df=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},Af=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},Nn=class extends Et{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},Ef=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Tf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},tr=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},gf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},Sf=class extends Et{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ei={configNotFound(t,i,r){return new Jn(t,i,r)},configLoad(t,i,r){return new Qi(t,i,r)},configValidation(t,i,r){return new df(t,i,r)},configMerge(t,i,r,n){return new Af(t,i,r,n)},envVar(t,i,r,n){return new Nn(t,i,r,n)},fileSystem(t,i,r){return new Ef(t,i,r)},typeGeneration(t,i,r){return new Tf(t,i,r)},schemaValidation(t,i,r){return new tr(t,i,r)},browserConfig(t,i,r,n){return new gf(t,i,r,n)},plugin(t,i,r){return new Sf(t,i,r)}},Vc={replace:"replace",concat:"concat",smart:"smart"},pc=/^https?:\/\//,_t=new Fn("bunfig",{showTags:!0}),Xt=new _f,Pc=at(hi.cwd(),"config"),vc=at(hi.cwd(),"src/generated")});function dy(t,i={}){let r=Cn.cwd();while(r.includes("storage"))r=uc(r,"..");let n=uc(r,t||"");if(i?.relative)return r$(Cn.cwd(),n);return n}var Ay=Cn.env.CLARITY_LOG_DIR||i$(dy(),"logs"),Xc={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ay,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn={...Xc},yA=(async()=>{try{let{loadConfig:t}=await my().then(()=>Oc),i=await t({name:"clarity",alias:"logging",defaultConfig:Xc,cwd:Cn.cwd()});if(i)Object.assign(jn,i)}catch{}return jn})();function X(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ey(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class Qc{async format(t){let i=await Ey(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Hi.pid,hostname:i(),environment:Hi.env.NODE_ENV||"development",platform:Hi.platform,version:Hi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Hi.env.NODE_ENV||Hi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},F=it,wA=it.red,Ty=it.green,mA=it.yellow,gy=it.blue,dA=it.magenta,AA=it.cyan,Nc=it.white,EA=it.gray,Sy=it.bgRed,Cy=it.bgYellow,TA=it.bgGray,jc=it.bold,gA=it.dim,SA=it.italic,CA=it.underline,RA=it.strikethrough,BA=it.reset,of={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ry={debug:"\uD83D\uDD0D",info:gy("ℹ"),success:Ty("✓"),warning:Cy(Nc(jc(" WARN "))),error:Sy(Nc(jc(" ERROR ")))};class Hn{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(t,i={}){this.name=t,this.config={...jn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Qc,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...of,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...of};return{...of,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:jn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await l$(this.config.logDirectory,wc.F_OK|wc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await c$(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!ln(this.currentLogFile))await ff(this.currentLogFile,"",{mode:420});if(e=yc(this.currentLogFile,"a",420),s$(e,l,{flag:"a"}),$c(e),e!==void 0)ef(e),e=void 0;if((await Ii(this.currentLogFile)).size===0){if(await ff(this.currentLogFile,l,{flag:"w",mode:420}),(await Ii(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let o=h;if(o.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(o.code)){if(f<s-1){let u=typeof o.message==="string"?o.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(o?.code&&["ENOSPC","EDQUOT"].includes(o.code))throw Error(`Disk quota exceeded or no space left on device: ${o.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",o),o}finally{if(e!==void 0)try{ef(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let o=l,u=typeof o.message==="string"?o.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((o)=>setTimeout(o,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,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 Oi(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 Oi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Oi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return nf(16).toString("hex")}generateKey(){return nf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=nf(16),n=n$("aes-256-gcm",i,r),e=bt.isBuffer(t)?t:bt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=bt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=dc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(bt.from(bt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Ii(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await cn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let o=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-o}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ii(r).catch(()=>null))try{if(await mc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await hn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await ff(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ii(r).catch(()=>null))await mc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await cn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await hn(Oi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=ac(t),n=f$(i),e=dc();await u$(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ln(this.currentLogFile))try{let t=yc(this.currentLogFile,"r+");$c(t),ef(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await hn(Oi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof C.env.NO_COLOR<"u",i=C.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=C.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${F.cyan(e)}`;if(!s)return h.trim();let o=c(h).trim().length,u=c(i).length,$=Math.max(1,l-2-o-u);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=F.underline(F.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>F.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>F.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>F.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>F.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>F.strikethrough(n)),i}supportsHyperlinks(){if(X())return!1;let t=C.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=C.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(h$(i)||i.startsWith("./")||i.startsWith("../"))i=o$(i);else return null;return ln(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Ry[t],$=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:F.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:F.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:u,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
105
- `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:F.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let o=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
106
- `;if(c)o+=`${c}
107
- `;if(o=o.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(o)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!X()&&C.stdout.isTTY)C.stdout.write(`
108
- `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":F.blue("◐"),tag:r,message:`${F.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
109
- `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.green("✓"),tag:o,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!X())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Hn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(X())throw Error("createReadStream is not supported in browser environments");if(!ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ac(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=bt.isBuffer(t)?t:bt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=e$("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),o=l.length+h.length,u=bt.allocUnsafe(o);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X()}isServerMode(){return!X()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
110
- `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,o=`└${"─".repeat(l)}┘`,u=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:F.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(h),showTimestamp:!1})),u.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(o),showTimestamp:!1}))}else if(!X())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
111
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();C.stdin.removeListener("data",r);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(o,u)=>{if(u==="%")return"%";if(h>=i.length)return o;let $=i[h++];switch(u){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return o}}),h<i.length)r+=` ${i.slice(h).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${F.blue("◐")} `;console.error(`${h}${l} ${F.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
112
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=F.green("━".repeat(n)),s=F.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",o=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",$=`\r${o}${u} ${c} ${l}${h}`,a=C.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,C.stdout.write(t.lastRenderedLine),i)C.stdout.write(`
113
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(X()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await cn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Oi(this.config.logDirectory,n);if(t.before)try{if((await Ii(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await hn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var UA=new Hn("stacks");class Wt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class th extends Wt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class _n extends Wt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class ih extends Wt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class rh extends Wt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wf extends Wt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class nh extends Wt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class eh extends Wt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wn extends Wt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class fh extends Wt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class sh extends Wt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Zi={configNotFound(t,i,r){return new th(t,i,r)},configLoad(t,i,r){return new _n(t,i,r)},configValidation(t,i,r){return new ih(t,i,r)},configMerge(t,i,r,n){return new rh(t,i,r,n)},envVar(t,i,r,n){return new Wf(t,i,r,n)},fileSystem(t,i,r){return new nh(t,i,r)},typeGeneration(t,i,r){return new eh(t,i,r)},schemaValidation(t,i,r){return new Wn(t,i,r)},browserConfig(t,i,r,n){return new fh(t,i,r,n)},plugin(t,i,r){return new sh(t,i,r)}};async function By(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class Yf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let o=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],o,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Rf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((o)=>this.formatEnvKey(o,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((o)=>o.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let o=un.env[l]||(h?un.env[h]:void 0);if(o!==void 0){if(n.verbose){let u=un.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(o,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof Wf)throw u;throw Zi.envVar(l,o,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Zi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(un.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
104
+ `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var bc,Zi,rr,Vc,D$,b$,Sc,wn,mf,st,z,V$,Cc,p$,Rc,P$,v$,lf,X$,Bc,Uc,cf,Q$,ty,iy,ry,mn,pc,ny,lt,ey,fy,Fc,An,Af,v,B,sy,Jc,ly,Nc,cy,hy,hf,uy,jc,_c,oy,uf,ay,$y,yy,wy,my,dn,Pc,Ay,dy="0.15.6",Et,Jn,tr,df,Ef,Nn,Tf,gf,ir,Sf,Cf,ei,vc,Xc,_t,Xt,Qc,th,Ey=E$(async()=>{bc=import.meta.require,Zi=new Uf,rr=new Ff,Vc={createKey:T$,isEquivalent:g$,estimateMemoryUsage:S$},D$=Sn(yf.cwd(),"config"),b$=Sn(yf.cwd(),"src/generated"),Sc=gn.env.CLARITY_LOG_DIR||Ha(B$(),"logs"),wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Sc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},mf=await U$(),st={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},z=st,V$=st.red,Cc=st.green,p$=st.yellow,Rc=st.blue,P$=st.magenta,v$=st.cyan,lf=st.white,X$=st.gray,Bc=st.bgRed,Uc=st.bgYellow,cf=st.bold,Q$=st.dim,ty=st.italic,iy=st.underline,ry=st.reset,mn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pc={debug:"\uD83D\uDD0D",info:Rc("ℹ"),success:Cc("✓"),warning:Uc(lf(cf(" WARN "))),error:Bc(lf(cf(" ERROR ")))},ny=new Bn("stacks"),lt=new Bn("bunfig",{showTags:!0}),ey=ot(Qi.cwd(),"config"),fy=ot(Qi.cwd(),"src/generated"),Fc=Tn.env.CLARITY_LOG_DIR||Ia(j$(),"logs"),An={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Af=await _$(),v={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},B=v,sy=v.red,Jc=v.green,ly=v.yellow,Nc=v.blue,cy=v.magenta,hy=v.cyan,hf=v.white,uy=v.gray,jc=v.bgRed,_c=v.bgYellow,oy=v.bgGray,uf=v.bold,ay=v.dim,$y=v.italic,yy=v.underline,wy=v.strikethrough,my=v.reset,dn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Pc={debug:"\uD83D\uDD0D",info:Nc("ℹ"),success:Jc("✓"),warning:_c(hf(uf(" WARN "))),error:jc(hf(uf(" ERROR ")))},Ay=new Fn("stacks"),Et=class extends Error{timestamp;context;constructor(i,r={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Jn=class extends Et{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},tr=class extends Et{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},df=class extends Et{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},Ef=class extends Et{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},Nn=class extends Et{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},Tf=class extends Et{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},gf=class extends Et{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ir=class extends Et{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},Sf=class extends Et{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},Cf=class extends Et{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ei={configNotFound(t,i,r){return new Jn(t,i,r)},configLoad(t,i,r){return new tr(t,i,r)},configValidation(t,i,r){return new df(t,i,r)},configMerge(t,i,r,n){return new Ef(t,i,r,n)},envVar(t,i,r,n){return new Nn(t,i,r,n)},fileSystem(t,i,r){return new Tf(t,i,r)},typeGeneration(t,i,r){return new gf(t,i,r)},schemaValidation(t,i,r){return new ir(t,i,r)},browserConfig(t,i,r,n){return new Sf(t,i,r,n)},plugin(t,i,r){return new Cf(t,i,r)}},vc={replace:"replace",concat:"concat",smart:"smart"},Xc=/^https?:\/\//,_t=new Fn("bunfig",{showTags:!0}),Xt=new Wf,Qc=at(hi.cwd(),"config"),th=at(hi.cwd(),"src/generated")});function Ty(t,i={}){let r=Cn.cwd();while(r.includes("storage"))r=yc(r,"..");let n=yc(r,t||"");if(i?.relative)return f$(Cn.cwd(),n);return n}var gy=Cn.env.CLARITY_LOG_DIR||e$(Ty(),"logs"),ih={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},jn={...ih},Ad=(async()=>{try{let{loadConfig:t}=await Ey().then(()=>Zc),i=await t({name:"clarity",alias:"logging",defaultConfig:ih,cwd:Cn.cwd()});if(i)Object.assign(jn,i)}catch{}return jn})();function X(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Sy(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class rh{async format(t){let i=await Sy(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Li.pid,hostname:i(),environment:Li.env.NODE_ENV||"development",platform:Li.platform,version:Li.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Li.env.NODE_ENV||Li.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},J=it,dd=it.red,Cy=it.green,Ed=it.yellow,Ry=it.blue,Td=it.magenta,gd=it.cyan,Wc=it.white,Sd=it.gray,By=it.bgRed,Uy=it.bgYellow,Cd=it.bgGray,Yc=it.bold,Rd=it.dim,Bd=it.italic,Ud=it.underline,Fd=it.strikethrough,Jd=it.reset,of={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Fy={debug:"\uD83D\uDD0D",info:Ry("ℹ"),success:Cy("✓"),warning:Uy(Wc(Yc(" WARN "))),error:By(Wc(Yc(" ERROR ")))};class Hn{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(t,i={}){this.name=t,this.config={...jn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new rh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??C.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...of,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...of};return{...of,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:jn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!X()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await u$(this.config.logDirectory,dc.F_OK|dc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await o$(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!ln(this.currentLogFile))await sf(this.currentLogFile,"",{mode:420});if(e=Ac(this.currentLogFile,"a",420),h$(e,l,{flag:"a"}),mc(e),e!==void 0)ff(e),e=void 0;if((await Oi(this.currentLogFile)).size===0){if(await sf(this.currentLogFile,l,{flag:"w",mode:420}),(await Oi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<s-1){let o=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let $=c*2**f;await new Promise((a)=>setTimeout(a,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(e!==void 0)try{ff(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let u=l,o=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Hi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Hi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Hi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(X())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ef(16).toString("hex")}generateKey(){return ef(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=ef(16),n=s$("aes-256-gcm",i,r),e=bt.isBuffer(t)?t:bt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=bt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Tc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(bt.from(bt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(X())return;if(!this.shouldWriteToFile())return;let t=await Oi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await cn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let u=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Oi(r).catch(()=>null))try{if(await Ec(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await hn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await sf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Oi(r).catch(()=>null))await Ec(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await cn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await hn(Hi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=wc(t),n=c$(i),e=Tc();await y$(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ln(this.currentLogFile))try{let t=Ac(this.currentLogFile,"r+");mc(t),ff(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!X()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await hn(Hi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?J.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||X())return!1;let t=typeof C.env.NO_COLOR<"u",i=C.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof C.stderr<"u"&&C.stderr.isTTY||typeof C.stdout<"u"&&C.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(a)=>a.replace(this.ANSI_PATTERN,"");if(!this.fancy){let a=[];if(s)a.push(i);if(f==="warning")a.push("WARN");else if(f==="error")a.push("ERROR");else if(r)a.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)a.push(n.replace(/[[\]]/g,""));return a.push(e),a.join(" ")}let l=C.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${J.cyan(e)}`;if(!s)return h.trim();let u=c(h).trim().length,o=c(i).length,$=Math.max(1,l-2-u-o);return`${h.trim()}${" ".repeat($)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=J.underline(J.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>J.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>J.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>J.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>J.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>J.strikethrough(n)),i}supportsHyperlinks(){if(X())return!1;let t=C.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=C.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(a$(i)||i.startsWith("./")||i.startsWith("../"))i=$$(i);else return null;return ln(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":Fy[t],$=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",a;switch(t){case"debug":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:J.gray(l),level:t}),console.error(a);break;case"info":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"success":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:J.green(l),level:t}),console.error(a);break;case"warning":a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.warn(a);break;case"error":if(a=this.formatConsoleMessage({timestamp:e,icon:o,tag:$,message:l,level:t}),console.error(a),c){let m=c.split(`
105
+ `);for(let y of m)if(y.trim()&&!y.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:J.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!X()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
106
+ `;if(c)u+=`${c}
107
+ `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!X()&&C.stdout.isTTY)C.stdout.write(`
108
+ `);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!X()&&C.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":J.blue("◐"),tag:r,message:`${J.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
109
+ `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":J.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!X())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Hn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(X())throw Error("createReadStream is not supported in browser environments");if(!ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=bt.isBuffer(t)?t:bt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=l$("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),u=l.length+h.length,o=bt.allocUnsafe(u);return l.copy(o,0),h.copy(o,l.length),o.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X()}isServerMode(){return!X()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
110
+ `),l=Math.max(...c.map(($)=>$.length))+2,h=`┌${"─".repeat(l)}┐`,u=`└${"─".repeat(l)}┘`,o=c.map(($)=>{return this.formatConsoleMessage({timestamp:r,message:J.cyan($),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(h),showTimestamp:!1})),o.forEach(($)=>console.error($)),console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(u),showTimestamp:!1}))}else if(!X())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
111
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(X())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${J.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();C.stdin.removeListener("data",r);try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!1)}catch{}C.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof C.stdin.setRawMode==="function")C.stdin.setRawMode(!0)}catch{}C.stdin.resume(),C.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(u,o)=>{if(o==="%")return"%";if(h>=i.length)return u;let $=i[h++];switch(o){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return u}}),h<i.length)r+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${J.blue("◐")} `;console.error(`${h}${l} ${J.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
112
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!C.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=J.green("━".repeat(n)),s=J.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?J.green("✓"):J.blue("▶"),o=this.options.showTags!==!1&&this.name?` ${J.gray(this.formatTag(this.name))}`:"",$=`\r${u}${o} ${c} ${l}${h}`,a=C.stdout.columns||80,m=" ".repeat(Math.max(0,a-$.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${$}${m}`,C.stdout.write(t.lastRenderedLine),i)C.stdout.write(`
113
+ `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||X()||!C.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(X()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await cn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Hi(this.config.logDirectory,n);if(t.before)try{if((await Oi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await hn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Nd=new Hn("stacks");class Wt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class nh extends Wt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class _n extends Wt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class eh extends Wt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class fh extends Wt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Yf extends Wt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class sh extends Wt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class lh extends Wt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Wn extends Wt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class ch extends Wt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class hh extends Wt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var Mi={configNotFound(t,i,r){return new nh(t,i,r)},configLoad(t,i,r){return new _n(t,i,r)},configValidation(t,i,r){return new eh(t,i,r)},configMerge(t,i,r,n){return new fh(t,i,r,n)},envVar(t,i,r,n){return new Yf(t,i,r,n)},fileSystem(t,i,r){return new sh(t,i,r)},typeGeneration(t,i,r){return new lh(t,i,r)},schemaValidation(t,i,r){return new Wn(t,i,r)},browserConfig(t,i,r,n){return new ch(t,i,r,n)},plugin(t,i,r){return new hh(t,i,r)}};async function Jy(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class If{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),o={...i};return this.processObject(o,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:o,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Bf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((u)=>this.formatEnvKey(u,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let u=on.env[l]||(h?on.env[h]:void 0);if(u!==void 0){if(n.verbose){let o=on.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,l,n.customParsers,n.configName)}catch(o){if(o instanceof Yf)throw o;throw Mi.envVar(l,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Mi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(on.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
114
114
 
115
115
  `;for(let n of t)r+=`${n.key}
116
116
  `,r+=` Type: ${n.type}
@@ -122,35 +122,36 @@ export type ConfigOf = Config
122
122
  `;r+=`| Variable | Type | Description | Example |
123
123
  `,r+=`|----------|------|-------------|----------|
124
124
  `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
125
- `;return r}}function Uy(t,i,r={}){return lh(t,i,r,new WeakMap)}function lh(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return ch(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return jy(t,i,r,n)}function ch(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Fy(t,i);case"smart":return Jy(t,i,n);default:return i}return i}function Fy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Cf(e,n)))r.push(n);return r}function Jy(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return Ny(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Ny(t,i,r){let n=[...i];for(let e of t){if(!Bt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Bt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function jy(t,i,r,n){let e=i;if(Bt(e)&&n.has(e))return n.get(e);let f={...t};if(Bt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=lh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ch(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function hh(t,i,r="replace"){return Uy(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Cf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Cf(t[r],i[r]))return!1;return!0}if(Bt(t)&&Bt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Cf(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class oh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=En.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!an(t))return null;try{let h=`?t=${Date.now()}`,o=await import(t+h),u=o.default||o,$="default"in o,a=Object.keys(o).length>0;if(!$&&!a)throw new _n(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new _n(t,Error("Configuration must export a valid object"),"unknown");let d={config:hh(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)En.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?Zi.configLoad(t,h):Zi.configLoad(t,Error(String(h)))}};if(s)return Rf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(uf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return By(async()=>{return an(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!an(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=uf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=uf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!an(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var Wy=/^https?:\/\//;class uh{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let o=[],u=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return o.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:o,warnings:u}}};if(c)return await Rf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!_y(i))throw new Wn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Wn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:Wy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Vt=new Hn("bunfig",{showTags:!0});function Yy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class ah{fileLoader=new oh;envProcessor=new Yf;validator=new uh;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let o=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!o&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||o))throw l;if(u&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Vt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw Vt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:o=!1}=t,u=f||Yn.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,u,s,c,h,o,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(a,$,l,n,o);let m=await this.loadHomeConfiguration(n,e,c,h,o,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,o);let y=await this.loadPackageJsonConfiguration(n,e,u,c,h,o,l);if(y)return $.push(Ct(u,"package.json")),this.finalizeResult(y,$,l,n,o);if($.push(...this.getAllSearchPaths(n,e,u,s)),i)throw Zi.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,o),warnings:[`No configuration file found for "${n}"${Yy(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?$n(t,e,s):e,o=this.getLocalDirectories(r,n);for(let u of o){if(s)Vt.info(`Searching for configuration in: ${u}`);let $=this.fileLoader.generateConfigPaths(t,u,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)Vt.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?$n(t,r,e):r,c=[Ct(Ui(),".config",t),Ct(Ui(),".config"),Ui()];for(let l of c){if(e)Vt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),o=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(o){if(e)Vt.success(`Configuration loaded from home directory: ${o.source.path}`);return o}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?$n(t,n,f):n;try{let l=Ct(r,"package.json");if(!Ua(l))return null;let h={};try{h=JSON.parse(Fa(l,"utf8"))}catch($){if(f)Vt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let o=h[t],u=t;if(!o&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){o=h[a],u=a;break}}}if(o&&typeof o==="object"&&!Array.isArray(o)){if(f)Vt.success(`Configuration loaded from package.json: ${u}`);return{config:hh(c,o,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Vt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$n(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Zi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return En.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);En.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Ct(t,"config"),Ct(t,".config"),i?Ct(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Ct(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Ct(Ui(),".config",t),Ct(Ui(),".config"),Ui()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var _A=new ah;function $n(t,i,r=!1){let n=new Yf,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,o]of Object.entries(s)){let u=[...c,h],$=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((y)=>y.toUpperCase()).join("")}`,`${e}_${u.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=Yn.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof o==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof o==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(o))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(o&&typeof o==="object"&&!Array.isArray(o))l[h]=f(o,u)}return l}return f(i)}var WA=Ct(Yn.cwd(),"config"),YA=Ct(Yn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Iy={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Of(If(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Of(If(),".stacks","ssl","stacks.localhost.crt"),keyPath:Of(If(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var $h=Iy;import{execSync as nr}from"node:child_process";import{homedir as My}from"node:os";import{join as zy}from"node:path";import{execSync as Ln}from"node:child_process";function yh(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Zn(t){try{let i=Ln(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return yh(i)}catch{return null}}function Oy(t){try{return Ln(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function Hy(t,i){try{let r=Ln(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((n)=>r.includes(`DNS:${n}`))}catch{return!1}}function Ly(t,i,r=443){try{return Ln(`echo | openssl s_client -connect ${t}:${r} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function Zy(t){let i=[];for(let r of t.split(`
126
- `)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var fi="-d -r trustRoot -p ssl -p basic",oi="/Library/Keychains/System.keychain",Hf="rpx.localhost";function er(){return zy(My(),"Library/Keychains/login.keychain-db")}function Lf(){return[oi,er()]}function wh(t,i=Hf){let r=nr(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let e of r.split(`
127
- `)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function Mn(t){if(process.platform!=="darwin")return;let i=Zn(t.caPath);if(!i)return;let r=t.commonName??Hf,n=t.keychains??Lf();for(let e of n)for(let f of wh(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))rr(`security delete-certificate -Z ${f} "${e}"`);else nr(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});w("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function fr(t,i,r){if(process.platform!=="darwin")return sr(t,r);try{let e=nr(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return w("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,r?.verbose),e}catch{return!1}}function sr(t,i){let r=Zn(t);if(!r)return!1;for(let n of Lf())try{let e=nr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let f of e.split(`
128
- `))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return w("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function Zf(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;Mn({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=er();try{nr(`security add-trusted-cert ${fi} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{rr(`security add-trusted-cert ${fi} -k ${oi} "${t}"`)}catch{return!1}return fr(t,r,{verbose:i.verbose})||sr(t,{verbose:i.verbose})}var si=null,Gy="rpx-root-ca.crt",qy="rpx-root-ca.key";function Gf(t){return{caCertPath:Q(t,Gy),caKeyPath:Q(t,qy)}}function f1(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:Gf(t)}}async function Ky(t,i){try{let[r,n]=await Promise.all([k.readFile(t.caCertPath,"utf8"),k.readFile(t.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return w("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:r,privateKey:n}}catch(r){return w("ssl",`No existing Root CA at ${t.caCertPath} (${r.code||r}), will create one`,i),null}}function mh(t){let i=new Set;i.add(t);let r=t.split(".");if(r.length>=2)i.add(`*.${r.slice(1).join(".")}`);return Array.from(i)}function gh(t){let r=zf(t).replace(/\*/g,"wildcard"),n=Q(Gn(),".stacks","ssl"),e=n;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:n,{caCertPath:t.https.caCertPath||Q(e,`${r}.ca.crt`),certPath:t.https.certPath||Q(e,`${r}.crt`),keyPath:t.https.keyPath||Q(e,`${r}.key`)};return{caCertPath:Q(e,`${r}.ca.crt`),certPath:Q(e,`${r}.crt`),keyPath:Q(e,`${r}.key`)}}function dh(t){let i=new Set;if(zn(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";mh(n).forEach((e)=>i.add(e))});else if(Eh(t)){let r=t.to||"rpx.localhost";mh(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function s1(t){w("ssl","Loading SSL configuration",t.verbose);let i={...$h,...t};if(t.https=Kf(i),!t.https?.keyPath&&!t.https?.certPath)return w("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let r=!t.https?.keyPath?"keyPath":"certPath";throw w("ssl",`Invalid SSL configuration - missing ${r}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{w("ssl","Reading SSL certificate files",t.verbose);let r=await k.readFile(t.https?.keyPath,"utf8"),n=await k.readFile(t.https?.certPath,"utf8");return w("ssl","SSL configuration loaded successfully",t.verbose),{key:r,cert:n}}catch(r){return w("ssl",`Failed to read certificates: ${r}`,t.verbose),null}}catch(r){throw w("ssl",`SSL configuration error: ${r}`,t.verbose),r}}async function l1(t,i){if(Yt.platform==="darwin")return xy(t,i);if(Yt.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)n(!0);else r(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function xy(t,i){if(Yt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(fr(t,r,{verbose:n}))return w("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return w("ssl","Trusting Root CA for browsers (login + system keychains)",n),Zf(t,{serverName:r,verbose:n})}catch{return!1}}async function Sh(t){if(si&&!t.forceRegenerate){w("ssl","Using cached SSL configuration",t.verbose);return}ky();let i=zn(t)?t.proxies.map((o)=>o.to):[t.to];w("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=Kf(t,t.verbose),n=r.basePath||Q(Gn(),".stacks","ssl");await k.mkdir(n,{recursive:!0});let e=Gf(n),f=await Ky(e,t.verbose),s=!1;if(!f){if(t.verbose)M.info("Generating Root CA certificate (one-time)...");f=await Ke(r);try{await Promise.all([k.writeFile(e.caCertPath,f.certificate),k.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,w("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(o){throw w("ssl",`Error saving Root CA files: ${o}`,t.verbose),Error(`Failed to save Root CA files: ${o}`)}}else w("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)M.info(`Generating host certificate for: ${i.join(", ")}`);let c=await xe({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([k.writeFile(r.certPath,c.certificate),k.writeFile(r.keyPath,c.privateKey),k.writeFile(r.caCertPath,f.certificate)]),w("ssl","Certificate files saved successfully",t.verbose)}catch(o){throw w("ssl",`Error saving certificate files: ${o}`,t.verbose),Error(`Failed to save certificate files: ${o}`)}if(s?!1:await Ch(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(w("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)M.success("Root CA is already trusted in system trust store");if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)M.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)M.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Yt.platform==="darwin")try{Mn({caPath:e.caCertPath,verbose:t.verbose});let o=er();try{Mi(`security add-trusted-cert ${fi} -k "${o}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(rr(`security add-trusted-cert ${fi} -k ${oi} "${e.caCertPath}"`),t.verbose)M.success("Successfully added Root CA to system trust store");h=!0;let u=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
125
+ `;return r}}function Ny(t,i,r={}){return uh(t,i,r,new WeakMap)}function uh(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return oh(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return Yy(t,i,r,n)}function oh(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return jy(t,i);case"smart":return _y(t,i,n);default:return i}return i}function jy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Rf(e,n)))r.push(n);return r}function _y(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return Wy(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Wy(t,i,r){let n=[...i];for(let e of t){if(!Bt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Bt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Yy(t,i,r,n){let e=i;if(Bt(e)&&n.has(e))return n.get(e);let f={...t};if(Bt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=uh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=oh(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ah(t,i,r="replace"){return Ny(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Rf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Rf(t[r],i[r]))return!1;return!0}if(Bt(t)&&Bt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Rf(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class $h{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=En.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!an(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),o=u.default||u,$="default"in u,a=Object.keys(u).length>0;if(!$&&!a)throw new _n(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new _n(t,Error("Configuration must export a valid object"),"unknown");let A={config:ah(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)En.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?Mi.configLoad(t,h):Mi.configLoad(t,Error(String(h)))}};if(s)return Bf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(af(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return Jy(async()=>{return an(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!an(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=af(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=af(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!an(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var Oy=/^https?:\/\//;class yh{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let u=[],o=[],$={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,$);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],$);else return this.validateWithJSONSchema(t,i,$)}catch(a){return u.push({path:"",message:`Validation failed: ${a}`,rule:"system"}),{isValid:!1,errors:u,warnings:o}}};if(c)return await Bf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Iy(i))throw new Wn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Wn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.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:Oy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Vt=new Hn("bunfig",{showTags:!0});function Hy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class wh{fileLoader=new $h;envProcessor=new If;validator=new yh;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let u=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!u&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),$=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&($||u))throw l;if(o&&(!h||!$))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Vt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw Vt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:u=!1}=t,o=f||Yn.cwd(),$=[],a=await this.loadLocalConfiguration(n,e,o,s,c,h,u,l,r);if(a)return $.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(a,$,l,n,u);let m=await this.loadHomeConfiguration(n,e,c,h,u,l);if(m)return $.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,$,l,n,u);let y=await this.loadPackageJsonConfiguration(n,e,o,c,h,u,l);if(y)return $.push(Ct(o,"package.json")),this.finalizeResult(y,$,l,n,u);if($.push(...this.getAllSearchPaths(n,e,o,s)),i)throw Mi.configNotFound(n,$,e);return{...await this.applyEnvironmentVariables(n,c,l,u),warnings:[`No configuration file found for "${n}"${Hy(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?$n(t,e,s):e,u=this.getLocalDirectories(r,n);for(let o of u){if(s)Vt.info(`Searching for configuration in: ${o}`);let $=this.fileLoader.generateConfigPaths(t,o,i),a=await this.fileLoader.tryLoadFromPaths($,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(a){if(s)Vt.success(`Configuration loaded from: ${a.source.path}`);return a}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?$n(t,r,e):r,c=[Ct(Fi(),".config",t),Ct(Fi(),".config"),Fi()];for(let l of c){if(e)Vt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),u=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(u){if(e)Vt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?$n(t,n,f):n;try{let l=Ct(r,"package.json");if(!Na(l))return null;let h={};try{h=JSON.parse(ja(l,"utf8"))}catch($){if(f)Vt.warn("Failed to parse package.json:",[$ instanceof Error?$:Error(String($))]);return null}let u=h[t],o=t;if(!u&&i){let $=Array.isArray(i)?i:[i];for(let a of $){if(!a)continue;if(h[a]){u=h[a],o=a;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Vt.success(`Configuration loaded from package.json: ${o}`);return{config:ah(c,u,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Vt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:$n(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Mi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return En.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);En.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Ct(t,"config"),Ct(t,".config"),i?Ct(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Ct(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Ct(Fi(),".config",t),Ct(Fi(),".config"),Fi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var Id=new wh;function $n(t,i,r=!1){let n=new If,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,u]of Object.entries(s)){let o=[...c,h],$=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((y)=>y.toUpperCase()).join("")}`,`${e}_${o.map((y)=>y.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],a,m;for(let y of $)if(a=Yn.env[y],a!==void 0){m=y;break}if(a!==void 0&&m)if(typeof u==="boolean")l[h]=["true","1","yes"].includes(a.toLowerCase());else if(typeof u==="number"){let y=Number(a);if(!Number.isNaN(y))l[h]=y}else if(Array.isArray(u))try{l[h]=JSON.parse(a)}catch{l[h]=a.split(",").map((y)=>y.trim())}else l[h]=a;else if(u&&typeof u==="object"&&!Array.isArray(u))l[h]=f(u,o)}return l}return f(i)}var Od=Ct(Yn.cwd(),"config"),Hd=Ct(Yn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Ly={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Hf(Of(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Hf(Of(),".stacks","ssl","stacks.localhost.crt"),keyPath:Hf(Of(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var mh=Ly;import{execSync as er}from"node:child_process";import{homedir as qy}from"node:os";import{join as Ky}from"node:path";import{execSync as Ln}from"node:child_process";function Ah(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Zn(t){try{let i=Ln(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return Ah(i)}catch{return null}}function Zy(t){try{return Ln(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function My(t,i){try{let r=Ln(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((n)=>r.includes(`DNS:${n}`))}catch{return!1}}function zy(t,i,r=443){try{return Ln(`echo | openssl s_client -connect ${t}:${r} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function Gy(t){let i=[];for(let r of t.split(`
126
+ `)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var fi="-d -r trustRoot -p ssl -p basic",ui="/Library/Keychains/System.keychain",Lf="rpx.localhost";function fr(){return Ky(qy(),"Library/Keychains/login.keychain-db")}function Zf(){return[ui,fr()]}function dh(t,i=Lf){let r=er(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let e of r.split(`
127
+ `)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function Mn(t){if(process.platform!=="darwin")return;let i=Zn(t.caPath);if(!i)return;let r=t.commonName??Lf,n=t.keychains??Zf();for(let e of n)for(let f of dh(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))nr(`security delete-certificate -Z ${f} "${e}"`);else er(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});w("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function sr(t,i,r){if(process.platform!=="darwin")return lr(t,r);try{let e=er(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return w("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,r?.verbose),e}catch{return!1}}function lr(t,i){let r=Zn(t);if(!r)return!1;for(let n of Zf())try{let e=er(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let f of e.split(`
128
+ `))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return w("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function Mf(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;Mn({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=fr();try{er(`security add-trusted-cert ${fi} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{nr(`security add-trusted-cert ${fi} -k ${ui} "${t}"`)}catch{return!1}return sr(t,r,{verbose:i.verbose})||lr(t,{verbose:i.verbose})}var si=null,xy="rpx-root-ca.crt",ky="rpx-root-ca.key";function qf(t){return{caCertPath:Q(t,xy),caKeyPath:Q(t,ky)}}function c1(t){return{certPath:Q(t,"rpx.localhost.crt"),keyPath:Q(t,"rpx.localhost.key"),caCertPath:Q(t,"rpx.localhost.ca.crt"),rootCA:qf(t)}}async function Dy(t,i){try{let[r,n]=await Promise.all([D.readFile(t.caCertPath,"utf8"),D.readFile(t.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return w("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:r,privateKey:n}}catch(r){return w("ssl",`No existing Root CA at ${t.caCertPath} (${r.code||r}), will create one`,i),null}}function Eh(t){let i=new Set;i.add(t);let r=t.split(".");if(r.length>=2)i.add(`*.${r.slice(1).join(".")}`);return Array.from(i)}function Rh(t){let r=Gf(t).replace(/\*/g,"wildcard"),n=Q(Gn(),".stacks","ssl"),e=n;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:n,{caCertPath:t.https.caCertPath||Q(e,`${r}.ca.crt`),certPath:t.https.certPath||Q(e,`${r}.crt`),keyPath:t.https.keyPath||Q(e,`${r}.key`)};return{caCertPath:Q(e,`${r}.ca.crt`),certPath:Q(e,`${r}.crt`),keyPath:Q(e,`${r}.key`)}}function Th(t){let i=new Set;if(zn(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";Eh(n).forEach((e)=>i.add(e))});else if(Sh(t)){let r=t.to||"rpx.localhost";Eh(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function h1(t){w("ssl","Loading SSL configuration",t.verbose);let i={...mh,...t};if(t.https=xf(i),!t.https?.keyPath&&!t.https?.certPath)return w("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let r=!t.https?.keyPath?"keyPath":"certPath";throw w("ssl",`Invalid SSL configuration - missing ${r}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{w("ssl","Reading SSL certificate files",t.verbose);let r=await D.readFile(t.https?.keyPath,"utf8"),n=await D.readFile(t.https?.certPath,"utf8");return w("ssl","SSL configuration loaded successfully",t.verbose),{key:r,cert:n}}catch(r){return w("ssl",`Failed to read certificates: ${r}`,t.verbose),null}}catch(r){throw w("ssl",`SSL configuration error: ${r}`,t.verbose),r}}async function u1(t,i){if(Yt.platform==="darwin")return by(t,i);if(Yt.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)n(!0);else r(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function by(t,i){if(Yt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(sr(t,r,{verbose:n}))return w("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return w("ssl","Trusting Root CA for browsers (login + system keychains)",n),Mf(t,{serverName:r,verbose:n})}catch{return!1}}async function Bh(t){if(si&&!t.forceRegenerate){w("ssl","Using cached SSL configuration",t.verbose);return}Vy();let i=zn(t)?t.proxies.map((u)=>u.to):[t.to];w("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=xf(t,t.verbose),n=r.basePath||Q(Gn(),".stacks","ssl");await D.mkdir(n,{recursive:!0});let e=qf(n),f=await Dy(e,t.verbose),s=!1;if(!f){if(t.verbose)Z.info("Generating Root CA certificate (one-time)...");f=await xe(r);try{await Promise.all([D.writeFile(e.caCertPath,f.certificate),D.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,w("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(u){throw w("ssl",`Error saving Root CA files: ${u}`,t.verbose),Error(`Failed to save Root CA files: ${u}`)}}else w("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)Z.info(`Generating host certificate for: ${i.join(", ")}`);let c=await ke({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([D.writeFile(r.certPath,c.certificate),D.writeFile(r.keyPath,c.privateKey),D.writeFile(r.caCertPath,f.certificate)]),w("ssl","Certificate files saved successfully",t.verbose)}catch(u){throw w("ssl",`Error saving certificate files: ${u}`,t.verbose),Error(`Failed to save certificate files: ${u}`)}if(s?!1:await Uh(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(w("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)Z.success("Root CA is already trusted in system trust store");if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)Z.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)Z.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Yt.platform==="darwin")try{Mn({caPath:e.caCertPath,verbose:t.verbose});let u=fr();try{zi(`security add-trusted-cert ${fi} -k "${u}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(nr(`security add-trusted-cert ${fi} -k ${ui} "${e.caCertPath}"`),t.verbose)Z.success("Successfully added Root CA to system trust store");h=!0;let o=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
129
129
  echo "Trusting RPX Root CA"
130
- sudo security add-trusted-cert ${fi} -k ${oi} "${e.caCertPath}"
130
+ sudo security add-trusted-cert ${fi} -k ${ui} "${e.caCertPath}"
131
131
  echo "Root CA trusted! Please restart your browser."
132
132
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
133
- `;await k.writeFile(u,$,{mode:493})}catch(o){if(t.verbose)M.warn(`Could not add Root CA to trust store automatically: ${o}`);let u=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
133
+ `;await D.writeFile(o,$,{mode:493})}catch(u){if(t.verbose)Z.warn(`Could not add Root CA to trust store automatically: ${u}`);let o=Q(n,"trust-rpx-cert.sh"),$=`#!/bin/bash
134
134
  echo "Trusting RPX Root CA"
135
- sudo security add-trusted-cert ${fi} -k ${oi} "${e.caCertPath}"
135
+ sudo security add-trusted-cert ${fi} -k ${ui} "${e.caCertPath}"
136
136
  echo "Root CA trusted! Please restart your browser."
137
137
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
138
- `;if(await k.writeFile(u,$,{mode:493}),t.verbose)M.info(`Created a trust helper script at: ${u}`),M.info(`If you're still having certificate issues, run: sh ${u}`)}else if(Yt.platform==="linux")try{let{exec:o}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",$=`
138
+ `;if(await D.writeFile(o,$,{mode:493}),t.verbose)Z.info(`Created a trust helper script at: ${o}`),Z.info(`If you're still having certificate issues, run: sh ${o}`)}else if(Yt.platform==="linux")try{let{exec:u}=await import("node:child_process"),o="/usr/local/share/ca-certificates/rpx",$=`
139
139
  mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
140
140
  cp "${e.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
141
141
  update-ca-certificates
142
142
  echo "RPX Root CA installed. Please restart your browser."
143
- `,a=Q(Mf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await k.writeFile(a,$,{mode:493}),await new Promise((m)=>{o(`sudo bash "${a}"`,(y)=>{if(y){if(t.verbose)M.warn(`Could not trust certificates: ${y}`);m(!1)}else{if(t.verbose)M.success("Successfully added certificates to system trust store");m(!0)}})}),await k.unlink(a).catch(()=>{}),h=!0}catch(o){if(t.verbose)M.warn(`Failed to trust certificates: ${o}`)}else if(Yt.platform==="win32")try{let o=`
143
+ `,a=Q(zf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await D.writeFile(a,$,{mode:493}),await new Promise((m)=>{u(`sudo bash "${a}"`,(y)=>{if(y){if(t.verbose)Z.warn(`Could not trust certificates: ${y}`);m(!1)}else{if(t.verbose)Z.success("Successfully added certificates to system trust store");m(!0)}})}),await D.unlink(a).catch(()=>{}),h=!0}catch(u){if(t.verbose)Z.warn(`Failed to trust certificates: ${u}`)}else if(Yt.platform==="win32")try{let u=`
144
144
  $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${e.caCertPath.replace(/\//g,"\\")}")
145
145
  $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
146
146
  $store.Open("ReadWrite")
147
147
  $store.Add($cert)
148
148
  $store.Close()
149
149
  Write-Host "Root CA trusted successfully!"
150
- `,u=Q(Mf.tmpdir(),"rpx-trust.ps1");if(await k.writeFile(u,o),Mi(`powershell -ExecutionPolicy Bypass -File "${u}"`),t.verbose)M.success("Successfully added certificate to Windows trust store");h=!0}catch(o){if(t.verbose)M.warn(`Could not trust certificate: ${o}`)}else try{await ke(c,f.certificate,r),h=!0}catch(o){if(t.verbose)M.warn(`Could not add certificate to trust store: ${o}`)}if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)M.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)M.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),M.warn("This will bypass the warning and you should only need to do it once")}function ky(){si=null}async function qf(t){if(!t)return null;if(si)return si;let i=Kf(t);try{let[r,n,e]=await Promise.all([k.access(i.keyPath).then(()=>!0).catch(()=>!1),k.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?k.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return w("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;w("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||Q(Gn(),".stacks","ssl"),h=Gf(l);if(!(c?await Ch(h.caCertPath,t):!0))return w("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[u,$,a]=await Promise.all([k.readFile(i.keyPath,"utf8"),k.readFile(i.certPath,"utf8"),e&&i.caCertPath?k.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(a&&!a.includes("-----BEGIN CERTIFICATE-----"))return w("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(zn(t))try{let{X509Certificate:m}=await import("node:crypto"),d=new m($).subjectAltName||"",g=t.proxies.map((I)=>I.to).filter((I)=>!d.includes(`DNS:${I}`));if(g.length>0)return w("ssl",`Certificate missing SANs for: ${g.join(", ")}, will regenerate`,t.verbose),null}catch(m){w("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return w("ssl","Successfully loaded existing certificates",t.verbose),si={key:u,cert:$,ca:a},si}catch(r){return w("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function Kf(t,i){let r=zf(t);w("ssl",`Primary domain: ${r}`,i);let n=gh(t),e=Q(Gn(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(dh(t)).map((c)=>({type:2,value:c}))};if(Ah(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(dh(t)).map((f)=>({type:2,value:f}))}}async function c1(t,i){let r=gh({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];w("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>Th(e,i)))}async function Ch(t,i){try{if(w("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Yt.platform==="darwin"){if(i?.serverName)return fr(t,i.serverName,{verbose:i.verbose});return sr(t,{verbose:i.verbose})}else if(Yt.platform==="win32")try{let n=Mi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!n)return w("ssl","Could not extract certificate subject",i?.verbose),!1;let e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(Mi(e).toString().includes(n))return w("ssl","Certificate found in trusted root store",i?.verbose),!0;return w("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return w("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Yt.platform==="linux")try{let n=Mi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",e=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of e)try{if(Mi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${n}"`).toString().includes(n))return w("ssl",`Certificate fingerprint found in ${f}`,i?.verbose),!0}catch{}return w("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return w("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return w("ssl",`Platform ${Yt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return w("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}function Bh(t,i){return async(r)=>{let n=new URL(r.url),f=(r.headers.get("host")||"").split(":")[0],s=t(f);if(!s)return w("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});let c=s.sourceHost,l=n.pathname,h=Rh(n.pathname,s.pathRewrites);if(h)c=h.targetHost,l=h.targetPath,w("request",`Path rewrite: ${n.pathname} → ${c}${l}`,i);let o=`http://${c}${l}${n.search}`;try{let u=new Headers(r.headers);if(u.set("host",c),s.changeOrigin)u.set("origin",`http://${s.sourceHost}`);u.set("x-forwarded-for","127.0.0.1"),u.set("x-forwarded-proto","https"),u.set("x-forwarded-host",f);let $=await fetch(o,{method:r.method,headers:u,body:r.body,redirect:"manual"});if(s.cleanUrls&&n.pathname.endsWith(".html")){let m=n.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let a=new Headers($.headers);return new Response($.body,{status:$.status,statusText:$.statusText,headers:a})}catch(u){return w("request",`Proxy error for ${f}: ${u}`,i),new Response(`Proxy Error: ${u}`,{status:502})}}}import*as qn from"node:fs";import*as $t from"node:fs/promises";import{homedir as Dy}from"node:os";import*as xf from"node:path";import*as Kn from"node:process";var by=/^[a-zA-Z0-9._-]+$/;function Gi(){return xf.join(Dy(),".stacks","rpx","registry.d")}function kf(t){return typeof t==="string"&&t.length>0&&t.length<=128&&by.test(t)}function Df(t,i){if(!kf(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return xf.join(t,`${i}.json`)}function Ht(t){if(!Number.isInteger(t)||t<=0)return!1;try{return Kn.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Uh(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&kf(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&r&&typeof i.createdAt==="string"}async function Vy(t){await $t.mkdir(t,{recursive:!0})}async function d1(t,i=Gi(),r){if(!Uh(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await Vy(i);let n=Df(i,t.id),e=`${n}.tmp.${Kn.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await $t.writeFile(e,f,{encoding:"utf8",mode:420}),await $t.rename(e,n),w("registry",`wrote entry ${t.id} → ${n}`,r)}catch(s){throw await $t.unlink(e).catch(()=>{}),s}}async function py(t,i=Gi(),r){let n=Df(i,t);try{await $t.unlink(n),w("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function Py(t,i=Gi(),r){let n=Df(i,t);try{let e=await $t.readFile(n,"utf8"),f=JSON.parse(e);if(!Uh(f))return w("registry",`entry ${t} failed validation, removing`,r),await $t.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return w("registry",`entry ${t} has invalid JSON, removing`,r),await $t.unlink(n).catch(()=>{}),null;throw e}}async function zi(t=Gi(),i){let r;try{r=await $t.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!kf(f))continue;let s=await Py(f,t,i);if(s)n.push(s)}return n}async function bf(t=Gi(),i){let r=await zi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!Ht(e.pid))w("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await py(e.id,t,i).catch(()=>{}),n++}return n}function Fh(t,i={}){let r=i.dir??Gi(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;qn.mkdirSync(r,{recursive:!0});let s=null,c=!1,l=null,h=!1,o=(d)=>{return JSON.stringify(d.map((A)=>({id:A.id,from:A.from,to:A.to,pid:A.pid,pathRewrites:A.pathRewrites,cleanUrls:A.cleanUrls,changeOrigin:A.changeOrigin})).sort((A,g)=>A.id.localeCompare(g.id)))},u=()=>{if(s=null,c)return;zi(r,f).then((d)=>{return l=o(d),t(d)}).catch((d)=>{w("registry",`watcher onChange failed: ${d}`,f)})},$=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(u,n)},m=setInterval(()=>{if(c||h)return;h=!0,zi(r,f).then((d)=>{if(o(d)!==l)$()}).catch((d)=>{w("registry",`watcher poll failed: ${d}`,f)}).finally(()=>{h=!1})},e),y=qn.watch(r,{persistent:!0},(d,A)=>{if(A&&/\.tmp\.\d+\.\d+$/.test(A))return;$()});return y.on("error",(d)=>{w("registry",`watcher error: ${d}`,f)}),$(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),y.close()}}}var Xy=5000;function yt(){return It.join(Jh(),".stacks","rpx")}function pf(t=yt()){return It.join(t,"daemon.pid")}async function cr(t=yt()){try{let i=await Lt.readFile(pf(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Qy(t=yt()){let i=await cr(t);return i!==null&&Ht(i)}async function tw(t=yt()){await Lt.mkdir(t,{recursive:!0});let i=pf(t);while(!0){try{let n=await Lt.open(i,"wx");try{await n.write(`${D.pid}
151
- `)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await cr(t);if(r!==null&&Ht(r))throw Error(`rpx daemon already running (pid=${r})`);await Lt.unlink(i).catch(()=>{})}}async function lr(t=yt()){await Lt.unlink(pf(t)).catch(()=>{})}function iw(t){return{sourceHost:new URL(t.from.startsWith("http")?t.from:`http://${t.from}`).host,cleanUrls:t.cleanUrls??!1,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function rw(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function nw(t,i){let r=await zi(i,t.verbose),n=[...new Set(r.map((o)=>o.to))],e=rw(n),f=[...new Set([e,...n,"rpx.localhost"])],s=It.join(Jh(),".stacks","ssl"),c=It.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:It.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:It.join(s,"rpx.localhost.key"),caCertPath:It.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((o)=>({from:"localhost:1",to:o}))}:{to:e,from:"localhost:1"}},h=await qf(l);if(!h)w("daemon","no usable cert on disk, generating one",t.verbose),await Sh(l),h=await qf(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function J1(t={}){let i=t.verbose??!1,r=t.rpxDir??yt(),n=t.registryDir??It.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??Xy,l=await tw(r),h=new Map,o=(J)=>h.get(J);function u(J){let Ot=new Map;for(let ar of J)Ot.set(ar.to,iw(ar));h=Ot,w("daemon",`routing table now covers ${Ot.size} host(s): ${Array.from(Ot.keys()).join(", ")||"<empty>"}`,i)}await bf(n,i).catch((J)=>{w("daemon",`initial gc failed: ${J}`,i)});let $=await zi(n,i);u($),await or({rpxDir:r,verbose:i}).catch((J)=>{w("daemon",`DNS reconcile on start failed: ${J}`,i)}),await Vf($,{rpxDir:r,verbose:i,ownerPid:D.pid}).catch((J)=>{w("daemon",`DNS setup on start failed: ${J}`,i)});let a=await nw(t,n),m=Bun.serve({port:e,hostname:s,tls:{key:a.key,cert:a.cert,ca:a.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Bh(o,i),error(J){return w("daemon",`https server error: ${J}`,i),new Response(`Server Error: ${J.message}`,{status:500})}}),y=null;if(f>0)y=Bun.serve({port:f,hostname:s,fetch(J){let Ot=new URL(J.url),ar=(J.headers.get("host")??Ot.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${ar}${Ot.pathname}${Ot.search}`}})}});if(i)M.success(`rpx daemon listening on https://${s}:${e}${y?` (http→https on :${f})`:""}`),M.info(`pid file: ${l}`),M.info(`registry: ${n}`);let d=Fh((J)=>{u(J),Vf(J,{rpxDir:r,verbose:i,ownerPid:D.pid}).catch((Ot)=>{w("daemon",`DNS sync on registry change failed: ${Ot}`,i)})},{dir:n,verbose:i}),A=setInterval(()=>{bf(n,i).then((J)=>{if(J>0)w("daemon",`gc reaped ${J} stale entries`,i)}).catch((J)=>{w("daemon",`periodic gc failed: ${J}`,i)})},c);if(typeof A.unref==="function")A.unref();let g=!1,I,O=new Promise((J)=>{I=J});async function H(){if(g)return O;if(g=!0,clearInterval(A),d.close(),m.stop(!1),y?.stop(!1),await hr({rpxDir:r,verbose:i}).catch((J)=>{w("daemon",`DNS teardown failed: ${J}`,i)}),await lr(r),i)M.info("rpx daemon stopped");return I(),O}let qi=(J)=>{w("daemon",`received ${J}, shutting down`,i),H().catch(()=>{})};return D.once("SIGINT",qi),D.once("SIGTERM",qi),{stop:H,done:O,httpsPort:typeof m.port==="number"?m.port:e,httpPort:y&&typeof y.port==="number"?y.port:f,pidPath:l}}function ew(){let t=D.execPath,i=It.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&D.argv[1])return[t,D.argv[1],"daemon:start"];return[t,"daemon:start"]}async function N1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1;await or({rpxDir:i,verbose:r}).catch((o)=>{w("daemon",`DNS reconcile before ensureDaemonRunning: ${o}`,r)});let n=await cr(i);if(n!==null&&Ht(n))return w("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)w("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await lr(i);await Lt.mkdir(i,{recursive:!0});let e=t.spawnCommand??ew();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");w("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=vy(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??D.cwd(),env:t.spawnEnv?{...D.env,...t.spawnEnv}:D.env});f.unref();let s=null;f.once("error",(o)=>{s=o});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let o=await cr(i);if(o!==null&&Ht(o))return w("daemon",`daemon registered with pid=${o}`,r),{pid:o,spawned:!0};await new Promise((u)=>setTimeout(u,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function j1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await cr(i);if(s===null||!Ht(s)){if(s!==null)await lr(i);return await or({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{D.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await lr(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+n;while(Date.now()<c){if(!Ht(s))return w("daemon",`daemon pid=${s} stopped cleanly`,r),{stopped:!0,pid:s,forced:!1};await new Promise((l)=>setTimeout(l,e))}if(!f)throw Error(`rpx daemon (pid=${s}) did not exit within ${n}ms`);w("daemon",`daemon pid=${s} did not exit, escalating to SIGKILL`,r);try{D.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await lr(i),await hr({rpxDir:i,verbose:r}).catch((l)=>{w("daemon",`DNS teardown after SIGKILL: ${l}`,r)}),{stopped:!0,pid:s,forced:!0}}async function _1(t={}){let i=t.rpxDir??yt();if(await Qy(i))return;await or({rpxDir:i,verbose:t.verbose})}import*as li from"node:fs/promises";import{homedir as fw}from"node:os";import*as Pf from"node:path";var xn=1,sw="dns-state.json",Nh=["com","test","dev","app","page","local","localhost","example","invalid"];function jh(){return Pf.join(fw(),".stacks","rpx")}function vf(t=jh()){return Pf.join(t,sw)}async function kn(t=jh()){try{let i=await li.readFile(vf(t),"utf8"),r=JSON.parse(i);if(r.version!==xn||!Array.isArray(r.resolvers))return null;return{version:xn,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _h(t,i){await li.mkdir(t,{recursive:!0}),await li.writeFile(vf(t),`${JSON.stringify(i,null,2)}
152
- `,"utf8")}async function Xf(t){await li.rm(vf(t),{force:!0})}function Wh(t){let i=t.trim().toLowerCase().replace(/\.$/,"");if(!i||i.includes("127.0.0.1"))return null;if(i==="localhost"||i.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(i))return null;return i}function lw(t){let i=Wh(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function Qf(t){let i=new Set;for(let r of t){let n=lw(r);if(n)i.add(n)}return Array.from(i).sort()}function ts(t){let i=new Set;for(let r of t){let n=Wh(r);if(n)i.add(n)}return Array.from(i).sort()}var is=15353,hw="# managed-by: rpx",Oh="/etc/resolver",wt=null,Dn=new Set;function ow(t){return{id:t.readUInt16BE(0),flags:t.readUInt16BE(2),qdcount:t.readUInt16BE(4),ancount:t.readUInt16BE(6),nscount:t.readUInt16BE(8),arcount:t.readUInt16BE(10)}}function Hh(t,i){let r=[],n=i;while(!0){let e=t[n];if(e===0){n++;break}if((e&192)===192){let f=t.readUInt16BE(n)&16383,{name:s}=Hh(t,f);r.push(s),n+=2;break}n++,r.push(t.subarray(n,n+e).toString("ascii")),n+=e}return{name:r.join("."),newOffset:n}}function uw(t,i){let{name:r,newOffset:n}=Hh(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function bn(t){let i=t.split("."),r=[];for(let n of i)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function aw(t,i,r){let n=[],e=Buffer.alloc(12);e.writeUInt16BE(t,0),e.writeUInt16BE(33152,2),e.writeUInt16BE(1,4),e.writeUInt16BE(1,6),e.writeUInt16BE(0,8),e.writeUInt16BE(0,10),n.push(e),n.push(bn(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(bn(i.name));let s=Buffer.alloc(10);if(s.writeUInt16BE(i.type,0),s.writeUInt16BE(1,2),s.writeUInt32BE(300,4),i.type===1){s.writeUInt16BE(4,8),n.push(s);let c=r.split(".").map((l)=>Number.parseInt(l,10));n.push(Buffer.from(c))}else if(i.type===28)s.writeUInt16BE(16,8),n.push(s),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return e.writeUInt16BE(33155,2),e.writeUInt16BE(0,6),Buffer.concat([e,bn(i.name),f]);return Buffer.concat(n)}function $w(t,i){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(t,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(bn(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),r.push(e),Buffer.concat(r)}async function yw(t,i){if(Qt.platform!=="darwin")return!1;let r=ts(t);if(r.length===0)return!1;if(wt){for(let n of r)Dn.add(n);return w("dns","DNS server already running merged domains",i),!0}return Dn=new Set(r),new Promise((n)=>{wt=cw.createSocket("udp4"),wt.on("error",(e)=>{w("dns",`DNS server error: ${e.message}`,i),wt?.close(),wt=null,n(!1)}),wt.on("message",(e,f)=>{try{let s=ow(e),{question:c}=uw(e,12);w("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let u of Dn)if(l===u||l.endsWith(`.${u}`)){h=!0;break}let o;if(h&&(c.type===1||c.type===28))o=aw(s.id,c,"127.0.0.1"),w("dns",`Responding with localhost for ${c.name}`,i);else o=$w(s.id,c),w("dns",`NXDOMAIN for ${c.name}`,i);wt?.send(o,f.port,f.address)}catch(s){w("dns",`Error processing DNS query: ${s}`,i)}}),wt.on("listening",()=>{let e=wt?.address();w("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),n(!0)});try{wt.bind(is,"127.0.0.1")}catch(e){w("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function Lh(t){if(wt)w("dns","Stopping DNS server",t),wt.close(),wt=null,Dn=new Set}function z1(){return wt!==null}function ww(){return`${hw}
150
+ `,o=Q(zf.tmpdir(),"rpx-trust.ps1");if(await D.writeFile(o,u),zi(`powershell -ExecutionPolicy Bypass -File "${o}"`),t.verbose)Z.success("Successfully added certificate to Windows trust store");h=!0}catch(u){if(t.verbose)Z.warn(`Could not trust certificate: ${u}`)}else try{await De(c,f.certificate,r),h=!0}catch(u){if(t.verbose)Z.warn(`Could not add certificate to trust store: ${u}`)}if(si={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)Z.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)Z.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),Z.warn("This will bypass the warning and you should only need to do it once")}function Vy(){si=null}async function Kf(t){if(!t)return null;if(si)return si;let i=xf(t);try{let[r,n,e]=await Promise.all([D.access(i.keyPath).then(()=>!0).catch(()=>!1),D.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?D.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return w("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;w("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||Q(Gn(),".stacks","ssl"),h=qf(l);if(!(c?await Uh(h.caCertPath,t):!0))return w("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[o,$,a]=await Promise.all([D.readFile(i.keyPath,"utf8"),D.readFile(i.certPath,"utf8"),e&&i.caCertPath?D.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(a&&!a.includes("-----BEGIN CERTIFICATE-----"))return w("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(zn(t))try{let{X509Certificate:m}=await import("node:crypto"),A=new m($).subjectAltName||"",g=t.proxies.map((O)=>O.to).filter((O)=>!A.includes(`DNS:${O}`));if(g.length>0)return w("ssl",`Certificate missing SANs for: ${g.join(", ")}, will regenerate`,t.verbose),null}catch(m){w("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return w("ssl","Successfully loaded existing certificates",t.verbose),si={key:o,cert:$,ca:a},si}catch(r){return w("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function xf(t,i){let r=Gf(t);w("ssl",`Primary domain: ${r}`,i);let n=Rh(t),e=Q(Gn(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(Th(t)).map((c)=>({type:2,value:c}))};if(gh(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(Th(t)).map((f)=>({type:2,value:f}))}}async function o1(t,i){let r=Rh({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];w("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>Ch(e,i)))}async function Uh(t,i){try{if(w("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Yt.platform==="darwin"){if(i?.serverName)return sr(t,i.serverName,{verbose:i.verbose});return lr(t,{verbose:i.verbose})}else if(Yt.platform==="win32")try{let n=zi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!n)return w("ssl","Could not extract certificate subject",i?.verbose),!1;let e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(zi(e).toString().includes(n))return w("ssl","Certificate found in trusted root store",i?.verbose),!0;return w("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return w("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Yt.platform==="linux")try{let n=zi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",e=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of e)try{if(zi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${n}"`).toString().includes(n))return w("ssl",`Certificate fingerprint found in ${f}`,i?.verbose),!0}catch{}return w("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return w("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return w("ssl",`Platform ${Yt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return w("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}function Jh(t,i){return async(r)=>{let n=new URL(r.url),f=(r.headers.get("host")||"").split(":")[0],s=t(f);if(!s)return w("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});let c=s.sourceHost,l=n.pathname,h=Fh(n.pathname,s.pathRewrites);if(h)c=h.targetHost,l=h.targetPath,w("request",`Path rewrite: ${n.pathname} → ${c}${l}`,i);let u=`http://${c}${l}${n.search}`;try{let o=new Headers(r.headers);if(o.set("host",c),s.changeOrigin)o.set("origin",`http://${s.sourceHost}`);o.set("x-forwarded-for","127.0.0.1"),o.set("x-forwarded-proto","https"),o.set("x-forwarded-host",f);let $=await fetch(u,{method:r.method,headers:o,body:r.body,redirect:"manual"});if(s.cleanUrls&&n.pathname.endsWith(".html")){let m=n.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let a=new Headers($.headers);return new Response($.body,{status:$.status,statusText:$.statusText,headers:a})}catch(o){return w("request",`Proxy error for ${f}: ${o}`,i),new Response(`Proxy Error: ${o}`,{status:502})}}}import*as qn from"node:fs";import*as $t from"node:fs/promises";import{homedir as py}from"node:os";import*as kf from"node:path";import*as Kn from"node:process";var Py=/^[a-zA-Z0-9._-]+$/;function qi(){return kf.join(py(),".stacks","rpx","registry.d")}function Df(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Py.test(t)}function bf(t,i){if(!Df(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return kf.join(t,`${i}.json`)}function It(t){if(!Number.isInteger(t)||t<=0)return!1;try{return Kn.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Nh(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0;return typeof i.id==="string"&&Df(i.id)&&typeof i.from==="string"&&i.from.length>0&&typeof i.to==="string"&&i.to.length>0&&r&&typeof i.createdAt==="string"}async function vy(t){await $t.mkdir(t,{recursive:!0})}async function T1(t,i=qi(),r){if(!Nh(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await vy(i);let n=bf(i,t.id),e=`${n}.tmp.${Kn.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await $t.writeFile(e,f,{encoding:"utf8",mode:420}),await $t.rename(e,n),w("registry",`wrote entry ${t.id} → ${n}`,r)}catch(s){throw await $t.unlink(e).catch(()=>{}),s}}async function Xy(t,i=qi(),r){let n=bf(i,t);try{await $t.unlink(n),w("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function Qy(t,i=qi(),r){let n=bf(i,t);try{let e=await $t.readFile(n,"utf8"),f=JSON.parse(e);if(!Nh(f))return w("registry",`entry ${t} failed validation, removing`,r),await $t.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return w("registry",`entry ${t} has invalid JSON, removing`,r),await $t.unlink(n).catch(()=>{}),null;throw e}}async function Gi(t=qi(),i){let r;try{r=await $t.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!Df(f))continue;let s=await Qy(f,t,i);if(s)n.push(s)}return n}async function Vf(t=qi(),i){let r=await Gi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!It(e.pid))w("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await Xy(e.id,t,i).catch(()=>{}),n++}return n}function jh(t,i={}){let r=i.dir??qi(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;qn.mkdirSync(r,{recursive:!0});let s=null,c=!1,l=null,h=!1,u=(A)=>{return JSON.stringify(A.map((d)=>({id:d.id,from:d.from,to:d.to,pid:d.pid,pathRewrites:d.pathRewrites,cleanUrls:d.cleanUrls,changeOrigin:d.changeOrigin})).sort((d,g)=>d.id.localeCompare(g.id)))},o=()=>{if(s=null,c)return;Gi(r,f).then((A)=>{return l=u(A),t(A)}).catch((A)=>{w("registry",`watcher onChange failed: ${A}`,f)})},$=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(o,n)},m=setInterval(()=>{if(c||h)return;h=!0,Gi(r,f).then((A)=>{if(u(A)!==l)$()}).catch((A)=>{w("registry",`watcher poll failed: ${A}`,f)}).finally(()=>{h=!1})},e),y=qn.watch(r,{persistent:!0},(A,d)=>{if(d&&/\.tmp\.\d+\.\d+$/.test(d))return;$()});return y.on("error",(A)=>{w("registry",`watcher error: ${A}`,f)}),$(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),y.close()}}}var tw=5000;function yt(){return Ot.join(Pf(),".stacks","rpx")}function xn(t=yt()){return Ot.join(t,"daemon.pid")}async function Ki(t=yt()){try{let i=await Lt.readFile(xn(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function iw(t=yt()){let i=await Ki(t);return i!==null&&It(i)}async function rw(t=yt()){await Lt.mkdir(t,{recursive:!0});let i=xn(t);while(!0){try{let n=await Lt.open(i,"wx");try{await n.write(`${U.pid}
151
+ `)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ki(t);if(r!==null&&It(r))throw Error(`rpx daemon already running (pid=${r})`);await Lt.unlink(i).catch(()=>{})}}async function cr(t=yt()){await Lt.unlink(xn(t)).catch(()=>{})}function nw(t){return{sourceHost:new URL(t.from.startsWith("http")?t.from:`http://${t.from}`).host,cleanUrls:t.cleanUrls??!1,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites}}function ew(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function fw(t,i){let r=await Gi(i,t.verbose),n=[...new Set(r.map((u)=>u.to))],e=ew(n),f=[...new Set([e,...n,"rpx.localhost"])],s=Ot.join(Pf(),".stacks","ssl"),c=Ot.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:Ot.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:Ot.join(s,"rpx.localhost.key"),caCertPath:Ot.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((u)=>({from:"localhost:1",to:u}))}:{to:e,from:"localhost:1"}},h=await Kf(l);if(!h)w("daemon","no usable cert on disk, generating one",t.verbose),await Bh(l),h=await Kf(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function sw(t,i,r,n){let e=U.env.SUDO_PASSWORD,f=U.env.HOME??Pf(),s=[U.execPath,...U.argv.slice(1)],c=[`HOME=${f}`,`PATH=${U.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");let l=e?["-S","-p","","env",...c,...s]:["-n","env",...c,...s];w("daemon",`elevating daemon via sudo for privileged ports ${i}/${r}`,n);let h=_h("sudo",l,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,o=null;if(h.once("error",(m)=>{u=m}),h.once("exit",(m)=>{o=m??0}),e&&h.stdin)h.stdin.write(`${e}
152
+ `),h.stdin.end();h.unref();let $=xn(t),a=Date.now()+15000;while(Date.now()<a){if(u)throw u;let m=await Ki(t);if(m!==null&&It(m)){if(n)Z.success(`rpx daemon elevated to root (pid=${m}, https on :${i})`);return{httpsPort:i,httpPort:r,pidPath:$,done:Promise.resolve(),stop:async()=>{try{U.kill(m,"SIGTERM")}catch{}}}}if(o!==null&&o!==0)throw Error(`rpx daemon could not elevate to bind :${i} (sudo exited ${o}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((y)=>setTimeout(y,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${t})`)}async function _1(t={}){let i=t.verbose??!1,r=t.rpxDir??yt(),n=t.registryDir??Ot.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??tw,l=e>0&&e<1024||f>0&&f<1024,h=typeof U.getuid==="function"&&U.getuid()===0;if(U.platform!=="win32"&&l&&!h)return sw(r,e,f,i);let u=await rw(r),o=new Map,$=(N)=>o.get(N);function a(N){let Ht=new Map;for(let ar of N)Ht.set(ar.to,nw(ar));o=Ht,w("daemon",`routing table now covers ${Ht.size} host(s): ${Array.from(Ht.keys()).join(", ")||"<empty>"}`,i)}await Vf(n,i).catch((N)=>{w("daemon",`initial gc failed: ${N}`,i)});let m=await Gi(n,i);a(m),await ur({rpxDir:r,verbose:i}).catch((N)=>{w("daemon",`DNS reconcile on start failed: ${N}`,i)}),await pf(m,{rpxDir:r,verbose:i,ownerPid:U.pid}).catch((N)=>{w("daemon",`DNS setup on start failed: ${N}`,i)});let y=await fw(t,n),A=Bun.serve({port:e,hostname:s,tls:{key:y.key,cert:y.cert,ca:y.ca,requestCert:!1,rejectUnauthorized:!1},fetch:Jh($,i),error(N){return w("daemon",`https server error: ${N}`,i),new Response(`Server Error: ${N.message}`,{status:500})}}),d=null;if(f>0)d=Bun.serve({port:f,hostname:s,fetch(N){let Ht=new URL(N.url),ar=(N.headers.get("host")??Ht.hostname).split(":")[0];return new Response(null,{status:301,headers:{Location:`https://${ar}${Ht.pathname}${Ht.search}`}})}});if(i)Z.success(`rpx daemon listening on https://${s}:${e}${d?` (http→https on :${f})`:""}`),Z.info(`pid file: ${u}`),Z.info(`registry: ${n}`);let g=jh((N)=>{a(N),pf(N,{rpxDir:r,verbose:i,ownerPid:U.pid}).catch((Ht)=>{w("daemon",`DNS sync on registry change failed: ${Ht}`,i)})},{dir:n,verbose:i}),O=setInterval(()=>{Vf(n,i).then((N)=>{if(N>0)w("daemon",`gc reaped ${N} stale entries`,i)}).catch((N)=>{w("daemon",`periodic gc failed: ${N}`,i)})},c);if(typeof O.unref==="function")O.unref();let L=!1,H,oi=new Promise((N)=>{H=N});async function fs(){if(L)return oi;if(L=!0,clearInterval(O),g.close(),A.stop(!1),d?.stop(!1),await hr({rpxDir:r,verbose:i}).catch((N)=>{w("daemon",`DNS teardown failed: ${N}`,i)}),await cr(r),i)Z.info("rpx daemon stopped");return H(),oi}let ss=(N)=>{w("daemon",`received ${N}, shutting down`,i),fs().catch(()=>{})};return U.once("SIGINT",ss),U.once("SIGTERM",ss),{stop:fs,done:oi,httpsPort:typeof A.port==="number"?A.port:e,httpPort:d&&typeof d.port==="number"?d.port:f,pidPath:u}}function lw(){let t=U.execPath,i=Ot.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&U.argv[1])return[t,U.argv[1],"daemon:start"];return[t,"daemon:start"]}async function W1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1;await ur({rpxDir:i,verbose:r}).catch((u)=>{w("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let n=await Ki(i);if(n!==null&&It(n))return w("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)w("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await cr(i);await Lt.mkdir(i,{recursive:!0});let e=t.spawnCommand??lw();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");w("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=_h(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??U.cwd(),env:t.spawnEnv?{...U.env,...t.spawnEnv}:U.env});f.unref();let s=null;f.once("error",(u)=>{s=u});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let u=await Ki(i);if(u!==null&&It(u))return w("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise((o)=>setTimeout(o,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function Y1(t={}){let i=t.rpxDir??yt(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await Ki(i);if(s===null||!It(s)){if(s!==null)await cr(i);return await ur({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{U.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await cr(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+n;while(Date.now()<c){if(!It(s))return w("daemon",`daemon pid=${s} stopped cleanly`,r),{stopped:!0,pid:s,forced:!1};await new Promise((l)=>setTimeout(l,e))}if(!f)throw Error(`rpx daemon (pid=${s}) did not exit within ${n}ms`);w("daemon",`daemon pid=${s} did not exit, escalating to SIGKILL`,r);try{U.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await cr(i),await hr({rpxDir:i,verbose:r}).catch((l)=>{w("daemon",`DNS teardown after SIGKILL: ${l}`,r)}),{stopped:!0,pid:s,forced:!0}}async function I1(t={}){let i=t.rpxDir??yt();if(await iw(i))return;await ur({rpxDir:i,verbose:t.verbose})}import*as li from"node:fs/promises";import{homedir as cw}from"node:os";import*as vf from"node:path";var kn=1,hw="dns-state.json",Wh=["com","test","dev","app","page","local","localhost","example","invalid"];function Yh(){return vf.join(cw(),".stacks","rpx")}function Xf(t=Yh()){return vf.join(t,hw)}async function Dn(t=Yh()){try{let i=await li.readFile(Xf(t),"utf8"),r=JSON.parse(i);if(r.version!==kn||!Array.isArray(r.resolvers))return null;return{version:kn,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ih(t,i){await li.mkdir(t,{recursive:!0}),await li.writeFile(Xf(t),`${JSON.stringify(i,null,2)}
153
+ `,"utf8")}async function Qf(t){await li.rm(Xf(t),{force:!0})}function Oh(t){let i=t.trim().toLowerCase().replace(/\.$/,"");if(!i||i.includes("127.0.0.1"))return null;if(i==="localhost"||i.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(i))return null;return i}function uw(t){let i=Oh(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function ts(t){let i=new Set;for(let r of t){let n=uw(r);if(n)i.add(n)}return Array.from(i).sort()}function is(t){let i=new Set;for(let r of t){let n=Oh(r);if(n)i.add(n)}return Array.from(i).sort()}var rs=15353,aw="# managed-by: rpx",Zh="/etc/resolver",wt=null,bn=new Set;function $w(t){return{id:t.readUInt16BE(0),flags:t.readUInt16BE(2),qdcount:t.readUInt16BE(4),ancount:t.readUInt16BE(6),nscount:t.readUInt16BE(8),arcount:t.readUInt16BE(10)}}function Mh(t,i){let r=[],n=i;while(!0){let e=t[n];if(e===0){n++;break}if((e&192)===192){let f=t.readUInt16BE(n)&16383,{name:s}=Mh(t,f);r.push(s),n+=2;break}n++,r.push(t.subarray(n,n+e).toString("ascii")),n+=e}return{name:r.join("."),newOffset:n}}function yw(t,i){let{name:r,newOffset:n}=Mh(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function Vn(t){let i=t.split("."),r=[];for(let n of i)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function ww(t,i,r){let n=[],e=Buffer.alloc(12);e.writeUInt16BE(t,0),e.writeUInt16BE(33152,2),e.writeUInt16BE(1,4),e.writeUInt16BE(1,6),e.writeUInt16BE(0,8),e.writeUInt16BE(0,10),n.push(e),n.push(Vn(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(Vn(i.name));let s=Buffer.alloc(10);if(s.writeUInt16BE(i.type,0),s.writeUInt16BE(1,2),s.writeUInt32BE(300,4),i.type===1){s.writeUInt16BE(4,8),n.push(s);let c=r.split(".").map((l)=>Number.parseInt(l,10));n.push(Buffer.from(c))}else if(i.type===28)s.writeUInt16BE(16,8),n.push(s),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return e.writeUInt16BE(33155,2),e.writeUInt16BE(0,6),Buffer.concat([e,Vn(i.name),f]);return Buffer.concat(n)}function mw(t,i){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(t,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(Vn(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),r.push(e),Buffer.concat(r)}async function Aw(t,i){if(Qt.platform!=="darwin")return!1;let r=is(t);if(r.length===0)return!1;if(wt){for(let n of r)bn.add(n);return w("dns","DNS server already running — merged domains",i),!0}return bn=new Set(r),new Promise((n)=>{wt=ow.createSocket("udp4"),wt.on("error",(e)=>{w("dns",`DNS server error: ${e.message}`,i),wt?.close(),wt=null,n(!1)}),wt.on("message",(e,f)=>{try{let s=$w(e),{question:c}=yw(e,12);w("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let o of bn)if(l===o||l.endsWith(`.${o}`)){h=!0;break}let u;if(h&&(c.type===1||c.type===28))u=ww(s.id,c,"127.0.0.1"),w("dns",`Responding with localhost for ${c.name}`,i);else u=mw(s.id,c),w("dns",`NXDOMAIN for ${c.name}`,i);wt?.send(u,f.port,f.address)}catch(s){w("dns",`Error processing DNS query: ${s}`,i)}}),wt.on("listening",()=>{let e=wt?.address();w("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),n(!0)});try{wt.bind(rs,"127.0.0.1")}catch(e){w("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function zh(t){if(wt)w("dns","Stopping DNS server",t),wt.close(),wt=null,bn=new Set}function K1(){return wt!==null}function dw(){return`${aw}
153
154
  nameserver 127.0.0.1
154
- port ${is}
155
- `}function ur(t){return Ih.join(Oh,t)}function mw(t){return t.includes("127.0.0.1")&&t.includes(String(is))}async function dw(t){try{return await Yh.readFile(ur(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function rs(t){if(Qt.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r()){w("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),w("dns","DNS cache flushed",t)}catch(n){w("dns",`Could not flush DNS cache: ${n}`,t)}}async function Aw(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js"),n=ww().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Oh} && printf "%b" "${n}" > ${ur(t)}'`;r(e),w("dns",`Created ${ur(t)}`,i)}async function Ew(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js");r(`rm -f ${ur(t)}`),w("dns",`Removed ${ur(t)}`,i)}async function G1(t,i){return Mh({domains:i??[],verbose:t})}async function Tw(t,i){if(Qt.platform!=="darwin")return!0;let{getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r())return w("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let n of t)await Aw(n,i);return await rs(i),!0}catch(n){return w("dns",`Failed to create resolver file: ${n}`,i),!1}}async function ns(t,i){if(Qt.platform!=="darwin")return;let{getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r())return;try{for(let n of t)await Ew(n,i);await rs(i)}catch(n){w("dns",`Failed to remove resolver files: ${n}`,i)}}async function Zh(t){if(Qt.platform!=="darwin")return[];let i=[];for(let r of Nh){let n=await dw(r);if(n&&mw(n))await ns([r],t),i.push(r)}return i}async function Mh(t){let i=t.rpxDir??yt(),r=ts(t.domains);if(r.length===0)return!1;let n=Qf(r);if(!await yw(r,t.verbose))return!1;if(!await Tw(n,t.verbose))return!1;let s={version:xn,resolvers:n,domains:r,ownerPid:t.ownerPid??Qt.pid,updatedAt:new Date().toISOString()};return await _h(i,s),!0}async function Vf(t,i={}){let r=t.map((l)=>l.to).filter(Boolean),n=i.rpxDir??yt(),e=Qf(r),c=((await kn(n))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await ns(c,i.verbose);if(e.length===0){Lh(i.verbose),await Xf(n);return}await Mh({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??Qt.pid})}async function hr(t={}){let i=t.rpxDir??yt();Lh(t.verbose);let n=(await kn(i))?.resolvers??[];await ns(n,t.verbose),await Zh(t.verbose),await Xf(i)}async function q1(t){await hr({verbose:t})}async function or(t={}){let i=t.rpxDir??yt(),r=await kn(i),n=r?.ownerPid!=null&&Ht(r.ownerPid);if(r&&!n){w("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,t.verbose),await hr(t);return}let e=await Zh(t.verbose);if(e.length>0)w("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await rs(t.verbose)}
156
- export{M as a,$h as b,yh as c,Zn as d,Oy as e,Hy as f,Ly as g,Zy as h,fi as i,oi as j,Hf as k,er as l,Lf as m,wh as n,Mn as o,fr as p,sr as q,Zf as r,Gf as s,f1 as t,s1 as u,l1 as v,Sh as w,ky as x,qf as y,Kf as z,c1 as A,Ch as B,Bh as C,Gi as D,kf as E,Ht as F,d1 as G,py as H,Py as I,zi as J,bf as K,Fh as L,xn as M,Nh as N,Wh as O,lw as P,Qf as Q,ts as R,is as S,hw as T,yw as U,Lh as V,z1 as W,ur as X,mw as Y,G1 as Z,Zh as _,Mh as $,Vf as aa,hr as ba,q1 as ca,or as da,yt as ea,pf as fa,cr as ga,Qy as ha,tw as ia,lr as ja,J1 as ka,ew as la,N1 as ma,j1 as na,_1 as oa};
155
+ port ${rs}
156
+ `}function or(t){return Lh.join(Zh,t)}function Ew(t){return t.includes("127.0.0.1")&&t.includes(String(rs))}async function Tw(t){try{return await Hh.readFile(or(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ns(t){if(Qt.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r()){w("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),w("dns","DNS cache flushed",t)}catch(n){w("dns",`Could not flush DNS cache: ${n}`,t)}}async function gw(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js"),n=dw().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Zh} && printf "%b" "${n}" > ${or(t)}'`;r(e),w("dns",`Created ${or(t)}`,i)}async function Sw(t,i){let{execSudoSync:r}=await import("./chunk-747af2w4.js");r(`rm -f ${or(t)}`),w("dns",`Removed ${or(t)}`,i)}async function x1(t,i){return qh({domains:i??[],verbose:t})}async function Cw(t,i){if(Qt.platform!=="darwin")return!0;let{getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r())return w("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let n of t)await gw(n,i);return await ns(i),!0}catch(n){return w("dns",`Failed to create resolver file: ${n}`,i),!1}}async function es(t,i){if(Qt.platform!=="darwin")return;let{getSudoPassword:r}=await import("./chunk-747af2w4.js");if(!r())return;try{for(let n of t)await Sw(n,i);await ns(i)}catch(n){w("dns",`Failed to remove resolver files: ${n}`,i)}}async function Gh(t){if(Qt.platform!=="darwin")return[];let i=[];for(let r of Wh){let n=await Tw(r);if(n&&Ew(n))await es([r],t),i.push(r)}return i}async function qh(t){let i=t.rpxDir??yt(),r=is(t.domains);if(r.length===0)return!1;let n=ts(r);if(!await Aw(r,t.verbose))return!1;if(!await Cw(n,t.verbose))return!1;let s={version:kn,resolvers:n,domains:r,ownerPid:t.ownerPid??Qt.pid,updatedAt:new Date().toISOString()};return await Ih(i,s),!0}async function pf(t,i={}){let r=t.map((l)=>l.to).filter(Boolean),n=i.rpxDir??yt(),e=ts(r),c=((await Dn(n))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await es(c,i.verbose);if(e.length===0){zh(i.verbose),await Qf(n);return}await qh({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??Qt.pid})}async function hr(t={}){let i=t.rpxDir??yt();zh(t.verbose);let n=(await Dn(i))?.resolvers??[];await es(n,t.verbose),await Gh(t.verbose),await Qf(i)}async function k1(t){await hr({verbose:t})}async function ur(t={}){let i=t.rpxDir??yt(),r=await Dn(i),n=r?.ownerPid!=null&&It(r.ownerPid);if(r&&!n){w("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,t.verbose),await hr(t);return}let e=await Gh(t.verbose);if(e.length>0)w("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await ns(t.verbose)}
157
+ export{Z as a,mh as b,Ah as c,Zn as d,Zy as e,My as f,zy as g,Gy as h,fi as i,ui as j,Lf as k,fr as l,Zf as m,dh as n,Mn as o,sr as p,lr as q,Mf as r,qf as s,c1 as t,h1 as u,u1 as v,Bh as w,Vy as x,Kf as y,xf as z,o1 as A,Uh as B,Jh as C,qi as D,Df as E,It as F,T1 as G,Xy as H,Qy as I,Gi as J,Vf as K,jh as L,kn as M,Wh as N,Oh as O,uw as P,ts as Q,is as R,rs as S,aw as T,Aw as U,zh as V,K1 as W,or as X,Ew as Y,x1 as Z,Gh as _,qh as $,pf as aa,hr as ba,k1 as ca,ur as da,yt as ea,xn as fa,Ki as ga,iw as ha,rw as ia,cr as ja,_1 as ka,lw as la,W1 as ma,Y1 as na,I1 as oa};